From: Fedor Indutny Date: Wed, 17 Dec 2014 13:30:04 +0000 (+0700) Subject: test: split test in parallel/sequential X-Git-Tag: v1.0.0-release~169 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=0e19476595729c850f07befea93e864822cd8459;p=platform%2Fupstream%2Fnodejs.git test: split test in parallel/sequential Reviewed-By: Ben Noordhuis PR-URL: https://github.com/iojs/io.js/pull/172 Fix: iojs/io.js#139 --- diff --git a/Makefile b/Makefile index 46dca45f6..114d198c9 100644 --- a/Makefile +++ b/Makefile @@ -90,15 +90,18 @@ distclean: -rm -rf node_modules test: all - $(PYTHON) tools/test.py --mode=release simple message + $(PYTHON) tools/test.py --mode=release message parallel sequential $(MAKE) jslint $(MAKE) cpplint +test-parallel: all + $(PYTHON) tools/test.py --mode=release parallel -J + test-http1: all - $(PYTHON) tools/test.py --mode=release --use-http1 simple message + $(PYTHON) tools/test.py --mode=release --use-http1 sequential parallel message test-valgrind: all - $(PYTHON) tools/test.py --mode=release --valgrind simple message + $(PYTHON) tools/test.py --mode=release --valgrind sequential parallel message test/gc/node_modules/weak/build/Release/weakref.node: @if [ ! -f $(NODE_EXE) ]; then make all; fi @@ -141,7 +144,7 @@ test-message: test-build $(PYTHON) tools/test.py message test-simple: all - $(PYTHON) tools/test.py simple + $(PYTHON) tools/test.py parallel sequential test-pummel: all wrk $(PYTHON) tools/test.py pummel diff --git a/test/fixtures/path.js b/test/fixtures/path.js new file mode 100644 index 000000000..21c08d3c6 --- /dev/null +++ b/test/fixtures/path.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This is actually more a fixture than a test. It is used to make +var common = require('../common'); +// sure that require('./path') and require('path') do different things. +// It has to be in the same directory as the test 'test-module-loading.js' +// and it has to have the same name as an internal module. +exports.path_func = function() { + return 'path_func'; +}; diff --git a/test/parallel/simple.status b/test/parallel/simple.status new file mode 100644 index 000000000..d310575f1 --- /dev/null +++ b/test/parallel/simple.status @@ -0,0 +1,4 @@ +prefix simple + +[$system==linux] +test-net-GH-5504 : PASS,FLAKY diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js new file mode 100644 index 000000000..84ea9249c --- /dev/null +++ b/test/parallel/test-assert.js @@ -0,0 +1,317 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var a = require('assert'); + +function makeBlock(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return f.apply(this, args); + }; +} + +assert.ok(common.indirectInstanceOf(a.AssertionError.prototype, Error), + 'a.AssertionError instanceof Error'); + +assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)'); + +assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)'); + +assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')')); + +assert.throws(makeBlock(a.ok, false), + a.AssertionError, 'ok(false)'); + +assert.doesNotThrow(makeBlock(a.ok, true), + a.AssertionError, 'ok(true)'); + +assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')'); + +assert.throws(makeBlock(a.equal, true, false), a.AssertionError, 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, null, null), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, null, undefined), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal'); + +assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal'); + +assert.doesNotThrow(makeBlock(a.notEqual, true, false), 'notEqual'); + +assert.throws(makeBlock(a.notEqual, true, true), + a.AssertionError, 'notEqual'); + +assert.throws(makeBlock(a.strictEqual, 2, '2'), + a.AssertionError, 'strictEqual'); + +assert.throws(makeBlock(a.strictEqual, null, undefined), + a.AssertionError, 'strictEqual'); + +assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), 'notStrictEqual'); + +// deepEquals joy! +// 7.2 +assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), + new Date(2000, 3, 14)), 'deepEqual date'); + +assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), + a.AssertionError, + 'deepEqual date'); + +// 7.3 +assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m)); +assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm)); +assert.throws(makeBlock(a.deepEqual, /ab/, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/g, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/i, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/m, /a/)); +assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im)); + +var re1 = /a/; +re1.lastIndex = 3; +assert.throws(makeBlock(a.deepEqual, re1, /a/)); + + +// 7.4 +assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual == check'); +assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual == check'); +assert.throws(makeBlock(a.deepEqual, 4, '5'), + a.AssertionError, + 'deepEqual == check'); + +// 7.5 +// having the same number of owned properties && the same set of keys +assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4}, {a: 4})); +assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'})); +assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4'])); +assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); +//(although not necessarily the same order), +assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); +var a1 = [1, 2, 3]; +var a2 = [1, 2, 3]; +a1.a = 'test'; +a1.b = true; +a2.b = true; +a2.a = 'test'; +assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); + +// having an identical prototype property +var nbRoot = { + toString: function() { return this.first + ' ' + this.last; } +}; + +function nameBuilder(first, last) { + this.first = first; + this.last = last; + return this; +} +nameBuilder.prototype = nbRoot; + +function nameBuilder2(first, last) { + this.first = first; + this.last = last; + return this; +} +nameBuilder2.prototype = nbRoot; + +var nb1 = new nameBuilder('Ryan', 'Dahl'); +var nb2 = new nameBuilder2('Ryan', 'Dahl'); + +assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); + +nameBuilder2.prototype = Object; +nb2 = new nameBuilder2('Ryan', 'Dahl'); +assert.throws(makeBlock(a.deepEqual, nb1, nb2), a.AssertionError); + +// String literal + object blew up my implementation... +assert.throws(makeBlock(a.deepEqual, 'a', {}), a.AssertionError); + +// Testing the throwing +function thrower(errorConstructor) { + throw new errorConstructor('test'); +} +var aethrow = makeBlock(thrower, a.AssertionError); +aethrow = makeBlock(thrower, a.AssertionError); + +// the basic calls work +assert.throws(makeBlock(thrower, a.AssertionError), + a.AssertionError, 'message'); +assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError); +assert.throws(makeBlock(thrower, a.AssertionError)); + +// if not passing an error, catch all. +assert.throws(makeBlock(thrower, TypeError)); + +// when passing a type, only catch errors of the appropriate type +var threw = false; +try { + a.throws(makeBlock(thrower, TypeError), a.AssertionError); +} catch (e) { + threw = true; + assert.ok(e instanceof TypeError, 'type'); +} +assert.equal(true, threw, + 'a.throws with an explicit error is eating extra errors', + a.AssertionError); +threw = false; + +// doesNotThrow should pass through all errors +try { + a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError); +} catch (e) { + threw = true; + assert.ok(e instanceof TypeError); +} +assert.equal(true, threw, + 'a.doesNotThrow with an explicit error is eating extra errors'); + +// key difference is that throwing our correct error makes an assertion error +try { + a.doesNotThrow(makeBlock(thrower, TypeError), TypeError); +} catch (e) { + threw = true; + assert.ok(e instanceof a.AssertionError); +} +assert.equal(true, threw, + 'a.doesNotThrow is not catching type matching errors'); + +assert.throws(function() {assert.ifError(new Error('test error'))}); +assert.doesNotThrow(function() {assert.ifError(null)}); +assert.doesNotThrow(function() {assert.ifError()}); + +// make sure that validating using constructor really works +threw = false; +try { + assert.throws( + function() { + throw ({}); + }, + Array + ); +} catch (e) { + threw = true; +} +assert.ok(threw, 'wrong constructor validation'); + +// use a RegExp to validate error message +a.throws(makeBlock(thrower, TypeError), /test/); + +// use a fn to validate error object +a.throws(makeBlock(thrower, TypeError), function(err) { + if ((err instanceof TypeError) && /test/.test(err)) { + return true; + } +}); + + +// GH-207. Make sure deepEqual doesn't loop forever on circular refs + +var b = {}; +b.b = b; + +var c = {}; +c.b = c; + +var gotError = false; +try { + assert.deepEqual(b, c); +} catch (e) { + gotError = true; +} + +// GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. +var args = (function() { return arguments; })(); +a.throws(makeBlock(a.deepEqual, [], args)); +a.throws(makeBlock(a.deepEqual, args, [])); + +console.log('All OK'); +assert.ok(gotError); + + +// #217 +function testAssertionMessage(actual, expected) { + try { + assert.equal(actual, ''); + } catch (e) { + assert.equal(e.toString(), + ['AssertionError:', expected, '==', '""'].join(' ')); + assert.ok(e.generatedMessage, "Message not marked as generated"); + } +} +testAssertionMessage(undefined, '"undefined"'); +testAssertionMessage(null, 'null'); +testAssertionMessage(true, 'true'); +testAssertionMessage(false, 'false'); +testAssertionMessage(0, '0'); +testAssertionMessage(100, '100'); +testAssertionMessage(NaN, '"NaN"'); +testAssertionMessage(Infinity, '"Infinity"'); +testAssertionMessage(-Infinity, '"-Infinity"'); +testAssertionMessage('', '""'); +testAssertionMessage('foo', '"foo"'); +testAssertionMessage([], '[]'); +testAssertionMessage([1, 2, 3], '[1,2,3]'); +testAssertionMessage(/a/, '"/a/"'); +testAssertionMessage(/abc/gim, '"/abc/gim"'); +testAssertionMessage(function f() {}, '"function f() {}"'); +testAssertionMessage({}, '{}'); +testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}'); +testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, + '{"a":"NaN","b":"Infinity","c":"-Infinity"}'); + +// #2893 +try { + assert.throws(function () { + assert.ifError(null); + }); +} catch (e) { + threw = true; + assert.equal(e.message, 'Missing expected exception..'); +} +assert.ok(threw); + +// #5292 +try { + assert.equal(1, 2); +} catch (e) { + assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2') + assert.ok(e.generatedMessage, 'Message not marked as generated'); +} + +try { + assert.equal(1, 2, 'oh no'); +} catch (e) { + assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no') + assert.equal(e.generatedMessage, false, + 'Message incorrectly marked as generated'); +} diff --git a/test/parallel/test-bad-unicode.js b/test/parallel/test-bad-unicode.js new file mode 100644 index 000000000..0e57909a6 --- /dev/null +++ b/test/parallel/test-bad-unicode.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + exception = null; + +try { + eval('"\\uc/ef"'); +} catch (e) { + exception = e; +} + +assert(exception instanceof SyntaxError); diff --git a/test/parallel/test-beforeexit-event-exit.js b/test/parallel/test-beforeexit-event-exit.js new file mode 100644 index 000000000..be6f2c607 --- /dev/null +++ b/test/parallel/test-beforeexit-event-exit.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +process.on('beforeExit', function() { + assert(false, 'exit should not allow this to occur'); +}); + +process.exit(); diff --git a/test/parallel/test-beforeexit-event.js b/test/parallel/test-beforeexit-event.js new file mode 100644 index 000000000..d1e209354 --- /dev/null +++ b/test/parallel/test-beforeexit-event.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var net = require('net'); +var util = require('util'); +var common = require('../common'); +var revivals = 0; +var deaths = 0; + +process.on('beforeExit', function() { deaths++; } ); + +process.once('beforeExit', tryImmediate); + +function tryImmediate() { + console.log('set immediate'); + setImmediate(function() { + revivals++; + process.once('beforeExit', tryTimer); + }); +} + +function tryTimer() { + console.log('set a timeout'); + setTimeout(function () { + console.log('timeout cb, do another once beforeExit'); + revivals++; + process.once('beforeExit', tryListen); + }, 1); +} + +function tryListen() { + console.log('create a server'); + net.createServer() + .listen(common.PORT) + .on('listening', function() { + revivals++; + this.close(); + }); +} + +process.on('exit', function() { + assert.equal(4, deaths); + assert.equal(3, revivals); +}); diff --git a/test/parallel/test-buffer-ascii.js b/test/parallel/test-buffer-ascii.js new file mode 100644 index 000000000..784597a48 --- /dev/null +++ b/test/parallel/test-buffer-ascii.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// ASCII conversion in node.js simply masks off the high bits, +// it doesn't do transliteration. +assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)'); + +// 71 characters, 78 bytes. The ’ character is a triple-byte sequence. +var input = 'C’est, graphiquement, la réunion d’un accent aigu ' + + 'et d’un accent grave.'; + +var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + + 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + + 'accent grave.'; + +var buf = Buffer(input); + +for (var i = 0; i < expected.length; ++i) { + assert.equal(buf.slice(i).toString('ascii'), expected.slice(i)); + + // Skip remainder of multi-byte sequence. + if (input.charCodeAt(i) > 65535) ++i; + if (input.charCodeAt(i) > 127) ++i; +} diff --git a/test/parallel/test-buffer-concat.js b/test/parallel/test-buffer-concat.js new file mode 100644 index 000000000..858d6924f --- /dev/null +++ b/test/parallel/test-buffer-concat.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var zero = []; +var one = [ new Buffer('asdf') ]; +var long = []; +for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); + +var flatZero = Buffer.concat(zero); +var flatOne = Buffer.concat(one); +var flatLong = Buffer.concat(long); +var flatLongLen = Buffer.concat(long, 40); + +assert(flatZero.length === 0); +assert(flatOne.toString() === 'asdf'); +assert(flatOne === one[0]); +assert(flatLong.toString() === (new Array(10+1).join('asdf'))); +assert(flatLongLen.toString() === (new Array(10+1).join('asdf'))); + +console.log("ok"); diff --git a/test/parallel/test-buffer-inspect.js b/test/parallel/test-buffer-inspect.js new file mode 100644 index 000000000..a13c69b4e --- /dev/null +++ b/test/parallel/test-buffer-inspect.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var util = require('util'); + +var buffer = require('buffer'); + +buffer.INSPECT_MAX_BYTES = 2; + +var b = new Buffer(4); +b.fill('1234'); + +var s = new buffer.SlowBuffer(4); +s.fill('1234'); + +var expected = ''; + +assert.strictEqual(util.inspect(b), expected); +assert.strictEqual(util.inspect(s), expected); + +b = new Buffer(2); +b.fill('12'); + +s = new buffer.SlowBuffer(2); +s.fill('12'); + +expected = ''; + +assert.strictEqual(util.inspect(b), expected); +assert.strictEqual(util.inspect(s), expected); + +buffer.INSPECT_MAX_BYTES = Infinity; + +assert.doesNotThrow(function() { + assert.strictEqual(util.inspect(b), expected); + assert.strictEqual(util.inspect(s), expected); +}); \ No newline at end of file diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js new file mode 100644 index 000000000..1a462bd0b --- /dev/null +++ b/test/parallel/test-buffer-slice.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Buffer = require('buffer').Buffer; + +var buff = new Buffer(Buffer.poolSize + 1); +var slicedBuffer = buff.slice(); +assert.equal(slicedBuffer.parent, + buff, + "slicedBufffer should have its parent set to the original " + + " buffer"); diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js new file mode 100644 index 000000000..bf742f934 --- /dev/null +++ b/test/parallel/test-buffer.js @@ -0,0 +1,1186 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Buffer = require('buffer').Buffer; +var SlowBuffer = require('buffer').SlowBuffer; +var smalloc = require('smalloc'); + +// counter to ensure unique value is always copied +var cntr = 0; + +var b = Buffer(1024); // safe constructor + +console.log('b.length == %d', b.length); +assert.strictEqual(1024, b.length); + +b[0] = -1; +assert.strictEqual(b[0], 255); + +for (var i = 0; i < 1024; i++) { + b[i] = i % 256; +} + +for (var i = 0; i < 1024; i++) { + assert.strictEqual(i % 256, b[i]); +} + +var c = new Buffer(512); +console.log('c.length == %d', c.length); +assert.strictEqual(512, c.length); + +// First check Buffer#fill() works as expected. + +assert.throws(function() { + Buffer(8).fill('a', -1); +}); + +assert.throws(function() { + Buffer(8).fill('a', 0, 9); +}); + +// Make sure this doesn't hang indefinitely. +Buffer(8).fill(''); + +var buf = new Buffer(64); +buf.fill(10); +for (var i = 0; i < buf.length; i++) + assert.equal(buf[i], 10); + +buf.fill(11, 0, buf.length >> 1); +for (var i = 0; i < buf.length >> 1; i++) + assert.equal(buf[i], 11); +for (var i = (buf.length >> 1) + 1; i < buf.length; i++) + assert.equal(buf[i], 10); + +buf.fill('h'); +for (var i = 0; i < buf.length; i++) + assert.equal('h'.charCodeAt(0), buf[i]); + +buf.fill(0); +for (var i = 0; i < buf.length; i++) + assert.equal(0, buf[i]); + +buf.fill(null); +for (var i = 0; i < buf.length; i++) + assert.equal(0, buf[i]); + +buf.fill(1, 16, 32); +for (var i = 0; i < 16; i++) + assert.equal(0, buf[i]); +for (; i < 32; i++) + assert.equal(1, buf[i]); +for (; i < buf.length; i++) + assert.equal(0, buf[i]); + +var buf = new Buffer(10); +buf.fill('abc'); +assert.equal(buf.toString(), 'abcabcabca'); +buf.fill('է'); +assert.equal(buf.toString(), 'էէէէէ'); + +// copy 512 bytes, from 0 to 512. +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, 0, 512); +console.log('copied %d bytes from b into c', copied); +assert.strictEqual(512, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// copy c into b, without specifying sourceEnd +b.fill(++cntr); +c.fill(++cntr); +var copied = c.copy(b, 0, 0); +console.log('copied %d bytes from c into b w/o sourceEnd', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(c[i], b[i]); +} + +// copy c into b, without specifying sourceStart +b.fill(++cntr); +c.fill(++cntr); +var copied = c.copy(b, 0); +console.log('copied %d bytes from c into b w/o sourceStart', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(c[i], b[i]); +} + +// copy longer buffer b to shorter c without targetStart +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c); +console.log('copied %d bytes from b into c w/o targetStart', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// copy starting near end of b to c +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); +console.log('copied %d bytes from end of b into beginning of c', copied); +assert.strictEqual(Math.floor(c.length / 2), copied); +for (var i = 0; i < Math.floor(c.length / 2); i++) { + assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); +} +for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) { + assert.strictEqual(c[c.length-1], c[i]); +} + +// try to copy 513 bytes, and check we don't overrun c +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, 0, 513); +console.log('copied %d bytes from b trying to overrun c', copied); +assert.strictEqual(c.length, copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// copy 768 bytes from b into b +b.fill(++cntr); +b.fill(++cntr, 256); +var copied = b.copy(b, 0, 256, 1024); +console.log('copied %d bytes from b into b', copied); +assert.strictEqual(768, copied); +for (var i = 0; i < b.length; i++) { + assert.strictEqual(cntr, b[i]); +} + +// copy string longer than buffer length (failure will segfault) +var bb = new Buffer(10); +bb.fill('hello crazy world'); + + +var caught_error = null; + +// try to copy from before the beginning of b +caught_error = null; +try { + var copied = b.copy(c, 0, 100, 10); +} catch (err) { + caught_error = err; +} + +// copy throws at negative sourceStart +assert.throws(function() { + Buffer(5).copy(Buffer(5), 0, -1); +}, RangeError); + +// check sourceEnd resets to targetEnd if former is greater than the latter +b.fill(++cntr); +c.fill(++cntr); +var copied = b.copy(c, 0, 0, 1025); +console.log('copied %d bytes from b into c', copied); +for (var i = 0; i < c.length; i++) { + assert.strictEqual(b[i], c[i]); +} + +// throw with negative sourceEnd +console.log('test copy at negative sourceEnd'); +assert.throws(function() { + b.copy(c, 0, 0, -1); +}, RangeError); + +// when sourceStart is greater than sourceEnd, zero copied +assert.equal(b.copy(c, 0, 100, 10), 0); + +// when targetStart > targetLength, zero copied +assert.equal(b.copy(c, 512, 0, 10), 0); + +var caught_error; + +// invalid encoding for Buffer.toString +caught_error = null; +try { + var copied = b.toString('invalid'); +} catch (err) { + caught_error = err; +} +assert.strictEqual('Unknown encoding: invalid', caught_error.message); + +// invalid encoding for Buffer.write +caught_error = null; +try { + var copied = b.write('test string', 0, 5, 'invalid'); +} catch (err) { + caught_error = err; +} +assert.strictEqual('Unknown encoding: invalid', caught_error.message); + +// try to create 0-length buffers +new Buffer(''); +new Buffer('', 'ascii'); +new Buffer('', 'binary'); +new Buffer(0); + +// try to write a 0-length string beyond the end of b +assert.throws(function() { + b.write('', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + +// throw when writing past bounds from the pool +assert.throws(function() { + b.write('a', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + +// try to copy 0 bytes worth of data into an empty buffer +b.copy(new Buffer(0), 0, 0, 0); + +// try to copy 0 bytes past the end of the target buffer +b.copy(new Buffer(0), 1, 1, 1); +b.copy(new Buffer(1), 1, 1, 1); + +// try to copy 0 bytes from past the end of the source buffer +b.copy(new Buffer(1), 0, 2048, 2048); + +// try to toString() a 0-length slice of a buffer, both within and without the +// valid buffer range +assert.equal(new Buffer('abc').toString('ascii', 0, 0), ''); +assert.equal(new Buffer('abc').toString('ascii', -100, -100), ''); +assert.equal(new Buffer('abc').toString('ascii', 100, 100), ''); + +// try toString() with a object as a encoding +assert.equal(new Buffer('abc').toString({toString: function() { + return 'ascii'; +}}), 'abc'); + +// testing for smart defaults and ability to pass string values as offset +var writeTest = new Buffer('abcdes'); +writeTest.write('n', 'ascii'); +writeTest.write('o', 'ascii', '1'); +writeTest.write('d', '2', 'ascii'); +writeTest.write('e', 3, 'ascii'); +writeTest.write('j', 'ascii', 4); +assert.equal(writeTest.toString(), 'nodejs'); + +var asciiString = 'hello world'; +var offset = 100; +for (var j = 0; j < 500; j++) { + + for (var i = 0; i < asciiString.length; i++) { + b[i] = asciiString.charCodeAt(i); + } + var asciiSlice = b.toString('ascii', 0, asciiString.length); + assert.equal(asciiString, asciiSlice); + + var written = b.write(asciiString, offset, 'ascii'); + assert.equal(asciiString.length, written); + var asciiSlice = b.toString('ascii', offset, offset + asciiString.length); + assert.equal(asciiString, asciiSlice); + + var sliceA = b.slice(offset, offset + asciiString.length); + var sliceB = b.slice(offset, offset + asciiString.length); + for (var i = 0; i < asciiString.length; i++) { + assert.equal(sliceA[i], sliceB[i]); + } + + // TODO utf8 slice tests +} + + +for (var j = 0; j < 100; j++) { + var slice = b.slice(100, 150); + assert.equal(50, slice.length); + for (var i = 0; i < 50; i++) { + assert.equal(b[100 + i], slice[i]); + } +} + + +// make sure only top level parent propagates from allocPool +var b = new Buffer(5); +var c = b.slice(0, 4); +var d = c.slice(0, 2); +assert.equal(b.parent, c.parent); +assert.equal(b.parent, d.parent); + +// also from a non-pooled instance +var b = new SlowBuffer(5); +var c = b.slice(0, 4); +var d = c.slice(0, 2); +assert.equal(b, c.parent); +assert.equal(b, d.parent); + + + +// Bug regression test +var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 +var buffer = new Buffer(32); +var size = buffer.write(testValue, 0, 'utf8'); +console.log('bytes written to buffer: ' + size); +var slice = buffer.toString('utf8', 0, size); +assert.equal(slice, testValue); + + +// Test triple slice +var a = new Buffer(8); +for (var i = 0; i < 8; i++) a[i] = i; +var b = a.slice(4, 8); +assert.equal(4, b[0]); +assert.equal(5, b[1]); +assert.equal(6, b[2]); +assert.equal(7, b[3]); +var c = b.slice(2, 4); +assert.equal(6, c[0]); +assert.equal(7, c[1]); + + +var d = new Buffer([23, 42, 255]); +assert.equal(d.length, 3); +assert.equal(d[0], 23); +assert.equal(d[1], 42); +assert.equal(d[2], 255); +assert.deepEqual(d, new Buffer(d)); + +var e = new Buffer('über'); +console.error('uber: \'%s\'', e.toString()); +assert.deepEqual(e, new Buffer([195, 188, 98, 101, 114])); + +var f = new Buffer('über', 'ascii'); +console.error('f.length: %d (should be 4)', f.length); +assert.deepEqual(f, new Buffer([252, 98, 101, 114])); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + var f = new Buffer('über', encoding); + console.error('f.length: %d (should be 8)', f.length); + assert.deepEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0])); + + var f = new Buffer('привет', encoding); + console.error('f.length: %d (should be 12)', f.length); + assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); + assert.equal(f.toString(encoding), 'привет'); + + var f = new Buffer([0, 0, 0, 0, 0]); + assert.equal(f.length, 5); + var size = f.write('あいうえお', encoding); + console.error('bytes written to buffer: %d (should be 4)', size); + assert.equal(size, 4); + assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00])); +}); + +var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D) +assert.equal(f.length, 4); +assert.deepEqual(f, new Buffer('3DD84DDC', 'hex')); + + +var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; +var g = new Buffer(arrayIsh); +assert.deepEqual(g, new Buffer([0, 1, 2, 3])); +var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; +g = new Buffer(strArrayIsh); +assert.deepEqual(g, new Buffer([0, 1, 2, 3])); + + +// +// Test toString('base64') +// +assert.equal('TWFu', (new Buffer('Man')).toString('base64')); + +// test that regular and URL-safe base64 both work +var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff]; +assert.deepEqual(Buffer('//++/++/++//', 'base64'), Buffer(expected)); +assert.deepEqual(Buffer('__--_--_--__', 'base64'), Buffer(expected)); + +// big example +var quote = 'Man is distinguished, not only by his reason, but by this ' + + 'singular passion from other animals, which is a lust ' + + 'of the mind, that by a perseverance of delight in the continued ' + + 'and indefatigable generation of knowledge, exceeds the short ' + + 'vehemence of any carnal pleasure.'; +var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24s' + + 'IGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltY' + + 'WxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZX' + + 'JzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmR' + + 'lZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo' + + 'ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='; +assert.equal(expected, (new Buffer(quote)).toString('base64')); + + +b = new Buffer(1024); +var bytesWritten = b.write(expected, 0, 'base64'); +assert.equal(quote.length, bytesWritten); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder ignores whitespace +var expectedWhite = expected.slice(0, 60) + ' \n' + + expected.slice(60, 120) + ' \n' + + expected.slice(120, 180) + ' \n' + + expected.slice(180, 240) + ' \n' + + expected.slice(240, 300) + '\n' + + expected.slice(300, 360) + '\n'; +b = new Buffer(1024); +bytesWritten = b.write(expectedWhite, 0, 'base64'); +assert.equal(quote.length, bytesWritten); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder on the constructor works +// even in the presence of whitespace. +b = new Buffer(expectedWhite, 'base64'); +assert.equal(quote.length, b.length); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + +// check that the base64 decoder ignores illegal chars +var expectedIllegal = expected.slice(0, 60) + ' \x80' + + expected.slice(60, 120) + ' \xff' + + expected.slice(120, 180) + ' \x00' + + expected.slice(180, 240) + ' \x98' + + expected.slice(240, 300) + '\x03' + + expected.slice(300, 360); +b = new Buffer(expectedIllegal, 'base64'); +assert.equal(quote.length, b.length); +assert.equal(quote, b.toString('ascii', 0, quote.length)); + + +assert.equal(new Buffer('', 'base64').toString(), ''); +assert.equal(new Buffer('K', 'base64').toString(), ''); + +// multiple-of-4 with padding +assert.equal(new Buffer('Kg==', 'base64').toString(), '*'); +assert.equal(new Buffer('Kio=', 'base64').toString(), '**'); +assert.equal(new Buffer('Kioq', 'base64').toString(), '***'); +assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****'); +assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****'); +assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******'); +assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******'); +assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********'); +assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********'); +assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(), + '**********'); +assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(), + '***********'); +assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(), + '************'); +assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(), + '*************'); +assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(), + '**************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(), + '***************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(), + '****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(), + '*****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(), + '******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(), + '*******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(), + '********************'); + +// no padding, not a multiple of 4 +assert.equal(new Buffer('Kg', 'base64').toString(), '*'); +assert.equal(new Buffer('Kio', 'base64').toString(), '**'); +assert.equal(new Buffer('KioqKg', 'base64').toString(), '****'); +assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****'); +assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******'); +assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********'); +assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********'); +assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********'); +assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(), + '*************'); +assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(), + '**************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(), + '****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(), + '*****************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(), + '*******************'); +assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(), + '********************'); + +// handle padding graciously, multiple-of-4 or not +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', + 'base64').length, 32); +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', + 'base64').length, 32); +assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', + 'base64').length, 32); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', + 'base64').length, 31); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', + 'base64').length, 31); +assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', + 'base64').length, 31); + +// This string encodes single '.' character in UTF-16 +var dot = new Buffer('//4uAA==', 'base64'); +assert.equal(dot[0], 0xff); +assert.equal(dot[1], 0xfe); +assert.equal(dot[2], 0x2e); +assert.equal(dot[3], 0x00); +assert.equal(dot.toString('base64'), '//4uAA=='); + +// Writing base64 at a position > 0 should not mangle the result. +// +// https://github.com/joyent/node/issues/402 +var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh']; +var buf = new Buffer(64); +var pos = 0; + +for (var i = 0; i < segments.length; ++i) { + pos += b.write(segments[i], pos, 'base64'); +} +assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!'); + +// Creating buffers larger than pool size. +var l = Buffer.poolSize + 5; +var s = ''; +for (i = 0; i < l; i++) { + s += 'h'; +} + +var b = new Buffer(s); + +for (i = 0; i < l; i++) { + assert.equal('h'.charCodeAt(0), b[i]); +} + +var sb = b.toString(); +assert.equal(sb.length, s.length); +assert.equal(sb, s); + + +// Single argument slice +b = new Buffer('abcde'); +assert.equal('bcde', b.slice(1).toString()); + +// byte length +assert.equal(14, Buffer.byteLength('Il était tué')); +assert.equal(14, Buffer.byteLength('Il était tué', 'utf8')); +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + assert.equal(24, Buffer.byteLength('Il était tué', encoding)); +}); +assert.equal(12, Buffer.byteLength('Il était tué', 'ascii')); +assert.equal(12, Buffer.byteLength('Il était tué', 'binary')); + +// slice(0,0).length === 0 +assert.equal(0, Buffer('hello').slice(0, 0).length); + +// test hex toString +console.log('Create hex string from buffer'); +var hexb = new Buffer(256); +for (var i = 0; i < 256; i++) { + hexb[i] = i; +} +var hexStr = hexb.toString('hex'); +assert.equal(hexStr, + '000102030405060708090a0b0c0d0e0f' + + '101112131415161718191a1b1c1d1e1f' + + '202122232425262728292a2b2c2d2e2f' + + '303132333435363738393a3b3c3d3e3f' + + '404142434445464748494a4b4c4d4e4f' + + '505152535455565758595a5b5c5d5e5f' + + '606162636465666768696a6b6c6d6e6f' + + '707172737475767778797a7b7c7d7e7f' + + '808182838485868788898a8b8c8d8e8f' + + '909192939495969798999a9b9c9d9e9f' + + 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + + 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + + 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + + 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' + + 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' + + 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); + +console.log('Create buffer from hex string'); +var hexb2 = new Buffer(hexStr, 'hex'); +for (var i = 0; i < 256; i++) { + assert.equal(hexb2[i], hexb[i]); +} + +// test an invalid slice end. +console.log('Try to slice off the end of the buffer'); +var b = new Buffer([1, 2, 3, 4, 5]); +var b2 = b.toString('hex', 1, 10000); +var b3 = b.toString('hex', 1, 5); +var b4 = b.toString('hex', 1); +assert.equal(b2, b3); +assert.equal(b2, b4); + + +function buildBuffer(data) { + if (Array.isArray(data)) { + var buffer = new Buffer(data.length); + data.forEach(function(v, k) { + buffer[k] = v; + }); + return buffer; + } + return null; +} + +var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]); + +console.log(x.inspect()); +assert.equal('', x.inspect()); + +var z = x.slice(4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(5, z.length); +assert.equal(0x6f, z[0]); +assert.equal(0xa3, z[1]); +assert.equal(0x62, z[2]); +assert.equal(0x61, z[3]); +assert.equal(0x72, z[4]); + +var z = x.slice(0); +console.log(z.inspect()); +console.log(z.length); +assert.equal(z.length, x.length); + +var z = x.slice(0, 4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(4, z.length); +assert.equal(0x81, z[0]); +assert.equal(0xa3, z[1]); + +var z = x.slice(0, 9); +console.log(z.inspect()); +console.log(z.length); +assert.equal(9, z.length); + +var z = x.slice(1, 4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(3, z.length); +assert.equal(0xa3, z[0]); + +var z = x.slice(2, 4); +console.log(z.inspect()); +console.log(z.length); +assert.equal(2, z.length); +assert.equal(0x66, z[0]); +assert.equal(0x6f, z[1]); + +assert.equal(0, Buffer('hello').slice(0, 0).length); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + var b = new Buffer(10); + b.write('あいうえお', encoding); + assert.equal(b.toString(encoding), 'あいうえお'); +}); + +// Binary encoding should write only one byte per character. +var b = Buffer([0xde, 0xad, 0xbe, 0xef]); +var s = String.fromCharCode(0xffff); +b.write(s, 0, 'binary'); +assert.equal(0xff, b[0]); +assert.equal(0xad, b[1]); +assert.equal(0xbe, b[2]); +assert.equal(0xef, b[3]); +s = String.fromCharCode(0xaaee); +b.write(s, 0, 'binary'); +assert.equal(0xee, b[0]); +assert.equal(0xad, b[1]); +assert.equal(0xbe, b[2]); +assert.equal(0xef, b[3]); + +// #1210 Test UTF-8 string includes null character +var buf = new Buffer('\0'); +assert.equal(buf.length, 1); +buf = new Buffer('\0\0'); +assert.equal(buf.length, 2); + +buf = new Buffer(2); +var written = buf.write(''); // 0byte +assert.equal(written, 0); +written = buf.write('\0'); // 1byte (v8 adds null terminator) +assert.equal(written, 1); +written = buf.write('a\0'); // 1byte * 2 +assert.equal(written, 2); +written = buf.write('あ'); // 3bytes +assert.equal(written, 0); +written = buf.write('\0あ'); // 1byte + 3bytes +assert.equal(written, 1); +written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes +assert.equal(written, 2); + +buf = new Buffer(10); +written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) +assert.equal(written, 9); +written = buf.write('あいう\0'); // 3bytes * 3 + 1byte +assert.equal(written, 10); + +// #243 Test write() with maxLength +var buf = new Buffer(4); +buf.fill(0xFF); +var written = buf.write('abcd', 1, 2, 'utf8'); +console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0xFF); + +buf.fill(0xFF); +written = buf.write('abcd', 1, 4); +console.log(buf); +assert.equal(written, 3); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0x63); + +buf.fill(0xFF); +written = buf.write('abcd', 'utf8', 1, 2); // legacy style +console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0x61); +assert.equal(buf[2], 0x62); +assert.equal(buf[3], 0xFF); + +buf.fill(0xFF); +written = buf.write('abcdef', 1, 2, 'hex'); +console.log(buf); +assert.equal(written, 2); +assert.equal(buf[0], 0xFF); +assert.equal(buf[1], 0xAB); +assert.equal(buf[2], 0xCD); +assert.equal(buf[3], 0xFF); + +['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { + buf.fill(0xFF); + written = buf.write('abcd', 0, 2, encoding); + console.log(buf); + assert.equal(written, 2); + assert.equal(buf[0], 0x61); + assert.equal(buf[1], 0x00); + assert.equal(buf[2], 0xFF); + assert.equal(buf[3], 0xFF); +}); + +// test offset returns are correct +var b = new Buffer(16); +assert.equal(4, b.writeUInt32LE(0, 0)); +assert.equal(6, b.writeUInt16LE(0, 4)); +assert.equal(7, b.writeUInt8(0, 6)); +assert.equal(8, b.writeInt8(0, 7)); +assert.equal(16, b.writeDoubleLE(0, 8)); + +// test unmatched surrogates not producing invalid utf8 output +// ef bf bd = utf-8 representation of unicode replacement character +// see https://codereview.chromium.org/121173009/ +buf = new Buffer('ab\ud800cd', 'utf8'); +assert.equal(buf[0], 0x61); +assert.equal(buf[1], 0x62); +assert.equal(buf[2], 0xef); +assert.equal(buf[3], 0xbf); +assert.equal(buf[4], 0xbd); +assert.equal(buf[5], 0x63); +assert.equal(buf[6], 0x64); + +// test for buffer overrun +buf = new Buffer([0, 0, 0, 0, 0]); // length: 5 +var sub = buf.slice(0, 4); // length: 4 +written = sub.write('12345', 'binary'); +assert.equal(written, 4); +assert.equal(buf[4], 0); + +// Check for fractional length args, junk length args, etc. +// https://github.com/joyent/node/issues/1758 +Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec +assert.equal(Buffer(-1).length, 0); +assert.equal(Buffer(NaN).length, 0); +assert.equal(Buffer(3.3).length, 3); +assert.equal(Buffer({length: 3.3}).length, 3); +assert.equal(Buffer({length: 'BAM'}).length, 0); + +// Make sure that strings are not coerced to numbers. +assert.equal(Buffer('99').length, 2); +assert.equal(Buffer('13.37').length, 5); + +// Ensure that the length argument is respected. +'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) { + assert.equal(Buffer(1).write('aaaaaa', 0, 1, enc), 1); +}); + +// Regression test, guard against buffer overrun in the base64 decoder. +var a = Buffer(3); +var b = Buffer('xxx'); +a.write('aaaaaaaa', 'base64'); +assert.equal(b.toString(), 'xxx'); + +// issue GH-3416 +Buffer(Buffer(0), 0, 0); + +[ 'hex', + 'utf8', + 'utf-8', + 'ascii', + 'binary', + 'base64', + 'ucs2', + 'ucs-2', + 'utf16le', + 'utf-16le' ].forEach(function(enc) { + assert.equal(Buffer.isEncoding(enc), true); + }); + +[ 'utf9', + 'utf-7', + 'Unicode-FTW', + 'new gnu gun' ].forEach(function(enc) { + assert.equal(Buffer.isEncoding(enc), false); + }); + + +// GH-5110 +(function () { + var buffer = new Buffer('test'), + string = JSON.stringify(buffer); + + assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + + assert.deepEqual(buffer, JSON.parse(string, function(key, value) { + return value && value.type === 'Buffer' + ? new Buffer(value.data) + : value; + })); +})(); + +// issue GH-7849 +(function() { + var buf = new Buffer('test'); + var json = JSON.stringify(buf); + var obj = JSON.parse(json); + var copy = new Buffer(obj); + + assert(buf.equals(copy)); +})(); + +// issue GH-4331 +assert.throws(function() { + new Buffer(0xFFFFFFFF); +}, RangeError); +assert.throws(function() { + new Buffer(0xFFFFFFFFF); +}, RangeError); + + +// attempt to overflow buffers, similar to previous bug in array buffers +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, 0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(0xffffffff); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, 0xffffffff); +}, RangeError); + + +// ensure negative values can't get past offset +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(-1); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, -1); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.readFloatLE(-1); +}, RangeError); + +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0.0, -1); +}, RangeError); + +// offset checks +var buf = new Buffer(0); + +assert.throws(function() { buf.readUInt8(0); }, RangeError); +assert.throws(function() { buf.readInt8(0); }, RangeError); + +var buf = new Buffer([0xFF]); + +assert.equal(buf.readUInt8(0), 255); +assert.equal(buf.readInt8(0), -1); + +[16, 32].forEach(function(bits) { + var buf = new Buffer(bits / 8 - 1); + + assert.throws(function() { buf['readUInt' + bits + 'BE'](0); }, + RangeError, + 'readUInt' + bits + 'BE'); + + assert.throws(function() { buf['readUInt' + bits + 'LE'](0); }, + RangeError, + 'readUInt' + bits + 'LE'); + + assert.throws(function() { buf['readInt' + bits + 'BE'](0); }, + RangeError, + 'readInt' + bits + 'BE()'); + + assert.throws(function() { buf['readInt' + bits + 'LE'](0); }, + RangeError, + 'readInt' + bits + 'LE()'); +}); + +[16, 32].forEach(function(bits) { + var buf = new Buffer([0xFF, 0xFF, 0xFF, 0xFF]); + + assert.equal(buf['readUInt' + bits + 'BE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readUInt' + bits + 'LE'](0), + (0xFFFFFFFF >>> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'BE'](0), + (0xFFFFFFFF >> (32 - bits))); + + assert.equal(buf['readInt' + bits + 'LE'](0), + (0xFFFFFFFF >> (32 - bits))); +}); + +// test for common read(U)IntLE/BE +(function() { + var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); + + assert.equal(buf.readUIntLE(0, 1), 0x01); + assert.equal(buf.readUIntBE(0, 1), 0x01); + assert.equal(buf.readUIntLE(0, 3), 0x030201); + assert.equal(buf.readUIntBE(0, 3), 0x010203); + assert.equal(buf.readUIntLE(0, 5), 0x0504030201); + assert.equal(buf.readUIntBE(0, 5), 0x0102030405); + assert.equal(buf.readUIntLE(0, 6), 0x060504030201); + assert.equal(buf.readUIntBE(0, 6), 0x010203040506); + assert.equal(buf.readIntLE(0, 1), 0x01); + assert.equal(buf.readIntBE(0, 1), 0x01); + assert.equal(buf.readIntLE(0, 3), 0x030201); + assert.equal(buf.readIntBE(0, 3), 0x010203); + assert.equal(buf.readIntLE(0, 5), 0x0504030201); + assert.equal(buf.readIntBE(0, 5), 0x0102030405); + assert.equal(buf.readIntLE(0, 6), 0x060504030201); + assert.equal(buf.readIntBE(0, 6), 0x010203040506); +})(); + +// test for common write(U)IntLE/BE +(function() { + var buf = new Buffer(3); + buf.writeUIntLE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); + assert.equal(buf.readUIntLE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeUIntBE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); + assert.equal(buf.readUIntBE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeIntLE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); + assert.equal(buf.readIntLE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeIntBE(0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); + assert.equal(buf.readIntBE(0, 3), 0x123456); + + buf = new Buffer(3); + buf.writeIntLE(-0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]); + assert.equal(buf.readIntLE(0, 3), -0x123456); + + buf = new Buffer(3); + buf.writeIntBE(-0x123456, 0, 3); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]); + assert.equal(buf.readIntBE(0, 3), -0x123456); + + buf = new Buffer(5); + buf.writeUIntLE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); + assert.equal(buf.readUIntLE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeUIntBE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); + assert.equal(buf.readUIntBE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeIntLE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); + assert.equal(buf.readIntLE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeIntBE(0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); + assert.equal(buf.readIntBE(0, 5), 0x1234567890); + + buf = new Buffer(5); + buf.writeIntLE(-0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]); + assert.equal(buf.readIntLE(0, 5), -0x1234567890); + + buf = new Buffer(5); + buf.writeIntBE(-0x1234567890, 0, 5); + assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]); + assert.equal(buf.readIntBE(0, 5), -0x1234567890); +})(); + +// test Buffer slice +(function() { + var buf = new Buffer('0123456789'); + assert.equal(buf.slice(-10, 10), '0123456789'); + assert.equal(buf.slice(-20, 10), '0123456789'); + assert.equal(buf.slice(-20, -10), ''); + assert.equal(buf.slice(0, -1), '012345678'); + assert.equal(buf.slice(2, -2), '234567'); + assert.equal(buf.slice(0, 65536), '0123456789'); + assert.equal(buf.slice(65536, 0), ''); + for (var i = 0, s = buf.toString(); i < buf.length; ++i) { + assert.equal(buf.slice(-i), s.slice(-i)); + assert.equal(buf.slice(0, -i), s.slice(0, -i)); + } + // try to slice a zero length Buffer + // see https://github.com/joyent/node/issues/5881 + SlowBuffer(0).slice(0, 1); + // make sure a zero length slice doesn't set the .parent attribute + assert.equal(Buffer(5).slice(0,0).parent, undefined); + // and make sure a proper slice does have a parent + assert.ok(typeof Buffer(5).slice(0, 5).parent === 'object'); +})(); + +// Make sure byteLength properly checks for base64 padding +assert.equal(Buffer.byteLength('aaa=', 'base64'), 2); +assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3); + +// Regression test for #5482: should throw but not assert in C++ land. +assert.throws(function() { + Buffer('', 'buffer'); +}, TypeError); + +// Regression test for #6111. Constructing a buffer from another buffer +// should a) work, and b) not corrupt the source buffer. +(function() { + var a = [0]; + for (var i = 0; i < 7; ++i) a = a.concat(a); + a = a.map(function(_, i) { return i }); + var b = Buffer(a); + var c = Buffer(b); + assert.equal(b.length, a.length); + assert.equal(c.length, a.length); + for (var i = 0, k = a.length; i < k; ++i) { + assert.equal(a[i], i); + assert.equal(b[i], i); + assert.equal(c[i], i); + } +})(); + + +assert.throws(function () { + new Buffer(smalloc.kMaxLength + 1); +}, RangeError); + +assert.throws(function () { + new SlowBuffer(smalloc.kMaxLength + 1); +}, RangeError); + +// Test truncation after decode +var crypto = require('crypto'); + +var b1 = new Buffer('YW55=======', 'base64'); +var b2 = new Buffer('YW55', 'base64'); + +assert.equal( + crypto.createHash('sha1').update(b1).digest('hex'), + crypto.createHash('sha1').update(b2).digest('hex') +); + +// Test Compare +var b = new Buffer(1).fill('a'); +var c = new Buffer(1).fill('c'); +var d = new Buffer(2).fill('aa'); + +assert.equal(b.compare(c), -1); +assert.equal(c.compare(d), 1); +assert.equal(d.compare(b), 1); +assert.equal(b.compare(d), -1); + +assert.equal(Buffer.compare(b, c), -1); +assert.equal(Buffer.compare(c, d), 1); +assert.equal(Buffer.compare(d, b), 1); +assert.equal(Buffer.compare(b, d), -1); + +assert.throws(function() { + var b = new Buffer(1); + Buffer.compare(b, 'abc'); +}); + +assert.throws(function() { + var b = new Buffer(1); + Buffer.compare('abc', b); +}); + +assert.throws(function() { + var b = new Buffer(1); + b.compare('abc'); +}); + +// Test Equals +var b = new Buffer(5).fill('abcdf'); +var c = new Buffer(5).fill('abcdf'); +var d = new Buffer(5).fill('abcde'); +var e = new Buffer(6).fill('abcdef'); + +assert.ok(b.equals(c)); +assert.ok(!c.equals(d)); +assert.ok(!d.equals(e)); + +assert.throws(function() { + var b = new Buffer(1); + b.equals('abc'); +}); diff --git a/test/parallel/test-c-ares.js b/test/parallel/test-c-ares.js new file mode 100644 index 000000000..3a3a9223d --- /dev/null +++ b/test/parallel/test-c-ares.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var dns = require('dns'); + + +// Try resolution without callback + +dns.lookup(null, function(error, result, addressType) { + assert.equal(null, result); + assert.equal(4, addressType); +}); + +dns.lookup('127.0.0.1', function(error, result, addressType) { + assert.equal('127.0.0.1', result); + assert.equal(4, addressType); +}); + +dns.lookup('::1', function(error, result, addressType) { + assert.equal('::1', result); + assert.equal(6, addressType); +}); + +// Try calling resolve with an unsupported type. +assert.throws(function() { + dns.resolve('www.google.com', 'HI'); +}, /Unknown type/); + +// Windows doesn't usually have an entry for localhost 127.0.0.1 in +// C:\Windows\System32\drivers\etc\hosts +// so we disable this test on Windows. +if (process.platform != 'win32') { + dns.resolve('127.0.0.1', 'PTR', function(error, domains) { + if (error) throw error; + assert.ok(Array.isArray(domains)); + }); +} diff --git a/test/parallel/test-child-process-buffering.js b/test/parallel/test-child-process-buffering.js new file mode 100644 index 000000000..3fb13b620 --- /dev/null +++ b/test/parallel/test-child-process-buffering.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var pwd_called = false; +var childClosed = false; +var childExited = false; + +function pwd(callback) { + var output = ''; + var child = common.spawnPwd(); + + child.stdout.setEncoding('utf8'); + child.stdout.on('data', function(s) { + console.log('stdout: ' + JSON.stringify(s)); + output += s; + }); + + child.on('exit', function(c) { + console.log('exit: ' + c); + assert.equal(0, c); + childExited = true; + }); + + child.on('close', function () { + callback(output); + pwd_called = true; + childClosed = true; + }); +} + + +pwd(function(result) { + console.dir(result); + assert.equal(true, result.length > 1); + assert.equal('\n', result[result.length - 1]); +}); + +process.on('exit', function() { + assert.equal(true, pwd_called); + assert.equal(true, childExited); + assert.equal(true, childClosed); +}); diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js new file mode 100644 index 000000000..b06e8e479 --- /dev/null +++ b/test/parallel/test-child-process-cwd.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var path = require('path'); + +var returns = 0; + +/* + Spawns 'pwd' with given options, then test + - whether the exit code equals forCode, + - optionally whether the stdout result matches forData + (after removing traling whitespace) +*/ +function testCwd(options, forCode, forData) { + var data = ''; + + var child = common.spawnPwd(options); + + child.stdout.setEncoding('utf8'); + + child.stdout.on('data', function(chunk) { + data += chunk; + }); + + child.on('exit', function(code, signal) { + assert.strictEqual(forCode, code); + }); + + child.on('close', function () { + forData && assert.strictEqual(forData, data.replace(/[\s\r\n]+$/, '')); + returns--; + }); + + returns++; + + return child; +} + +// Assume these exist, and 'pwd' gives us the right directory back +if (process.platform == 'win32') { + testCwd({cwd: process.env.windir}, 0, process.env.windir); + testCwd({cwd: 'c:\\'}, 0, 'c:\\'); +} else { + testCwd({cwd: '/dev'}, 0, '/dev'); + testCwd({cwd: '/'}, 0, '/'); +} + +// Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT +(function() { + var errors = 0; + + testCwd({cwd: 'does-not-exist'}, -1).on('error', function(e) { + assert.equal(e.code, 'ENOENT'); + errors++; + }); + + process.on('exit', function() { + assert.equal(errors, 1); + }); +})(); + +// Spawn() shouldn't try to chdir() so this should just work +testCwd(undefined, 0); +testCwd({}, 0); +testCwd({cwd: ''}, 0); +testCwd({cwd: undefined}, 0); +testCwd({cwd: null}, 0); + +// Check whether all tests actually returned +assert.notEqual(0, returns); +process.on('exit', function() { + assert.equal(0, returns); +}); diff --git a/test/parallel/test-child-process-default-options.js b/test/parallel/test-child-process-default-options.js new file mode 100644 index 000000000..57ff60441 --- /dev/null +++ b/test/parallel/test-child-process-default-options.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var isWindows = process.platform === 'win32'; + +process.env.HELLO = 'WORLD'; + +if (isWindows) { + var child = spawn('cmd.exe', ['/c', 'set'], {}); +} else { + var child = spawn('/usr/bin/env', [], {}); +} + +var response = ''; + +child.stdout.setEncoding('utf8'); + +child.stdout.on('data', function(chunk) { + console.log('stdout: ' + chunk); + response += chunk; +}); + +process.on('exit', function() { + assert.ok(response.indexOf('HELLO=WORLD') >= 0, + 'spawn did not use process.env as default'); +}); diff --git a/test/parallel/test-child-process-detached.js b/test/parallel/test-child-process-detached.js new file mode 100644 index 000000000..10ce5d152 --- /dev/null +++ b/test/parallel/test-child-process-detached.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); + +var spawn = require('child_process').spawn; +var childPath = path.join(__dirname, '..', 'fixtures', 'parent-process-nonpersistent.js'); +var persistentPid = -1; + +var child = spawn(process.execPath, [ childPath ]); + +child.stdout.on('data', function (data) { + persistentPid = parseInt(data, 10); +}); + +process.on('exit', function () { + assert(persistentPid !== -1); + assert.throws(function () { + process.kill(child.pid); + }); + assert.doesNotThrow(function () { + process.kill(persistentPid); + }); +}); + diff --git a/test/parallel/test-child-process-disconnect.js b/test/parallel/test-child-process-disconnect.js new file mode 100644 index 000000000..5902be8f1 --- /dev/null +++ b/test/parallel/test-child-process-disconnect.js @@ -0,0 +1,118 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); + +// child +if (process.argv[2] === 'child') { + + // Check that the 'disconnect' event is deferred to the next event loop tick. + var disconnect = process.disconnect; + process.disconnect = function() { + disconnect.apply(this, arguments); + // If the event is emitted synchronously, we're too late by now. + process.once('disconnect', common.mustCall(disconnectIsNotAsync)); + // The funky function name makes it show up legible in mustCall errors. + function disconnectIsNotAsync() {} + }; + + var server = net.createServer(); + + server.on('connection', function(socket) { + + socket.resume(); + + process.on('disconnect', function() { + socket.end((process.connected).toString()); + }); + + // when the socket is closed, we will close the server + // allowing the process to self terminate + socket.on('end', function() { + server.close(); + }); + + socket.write('ready'); + }); + + // when the server is ready tell parent + server.on('listening', function() { + process.send('ready'); + }); + + server.listen(common.PORT); + +} else { + // testcase + var child = fork(process.argv[1], ['child']); + + var childFlag = false; + var childSelfTerminate = false; + var parentEmit = false; + var parentFlag = false; + + // when calling .disconnect the event should emit + // and the disconnected flag should be true. + child.on('disconnect', function() { + parentEmit = true; + parentFlag = child.connected; + }); + + // the process should also self terminate without using signals + child.on('exit', function() { + childSelfTerminate = true; + }); + + // when child is listening + child.on('message', function(msg) { + if (msg === 'ready') { + + // connect to child using TCP to know if disconnect was emitted + var socket = net.connect(common.PORT); + + socket.on('data', function(data) { + data = data.toString(); + + // ready to be disconnected + if (data === 'ready') { + child.disconnect(); + assert.throws(child.disconnect.bind(child), Error); + return; + } + + // disconnect is emitted + childFlag = (data === 'true'); + }); + + } + }); + + process.on('exit', function() { + assert.equal(childFlag, false); + assert.equal(parentFlag, false); + + assert.ok(childSelfTerminate); + assert.ok(parentEmit); + }); +} diff --git a/test/parallel/test-child-process-double-pipe.js b/test/parallel/test-child-process-double-pipe.js new file mode 100644 index 000000000..c09dfa885 --- /dev/null +++ b/test/parallel/test-child-process-double-pipe.js @@ -0,0 +1,120 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var is_windows = process.platform === 'win32'; + +var common = require('../common'); +var assert = require('assert'), + os = require('os'), + util = require('util'), + spawn = require('child_process').spawn; + +// We're trying to reproduce: +// $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ + +var grep, sed, echo; + +if (is_windows) { + grep = spawn('grep', ['--binary', 'o']), + sed = spawn('sed', ['--binary', 's/o/O/']), + echo = spawn('cmd.exe', + ['/c', 'echo', 'hello&&', 'echo', + 'node&&', 'echo', 'and&&', 'echo', 'world']); +} else { + grep = spawn('grep', ['o']), + sed = spawn('sed', ['s/o/O/']), + echo = spawn('echo', ['hello\nnode\nand\nworld\n']); +} + +/* + * grep and sed hang if the spawn function leaks file descriptors to child + * processes. + * This happens when calling pipe(2) and then forgetting to set the + * FD_CLOEXEC flag on the resulting file descriptors. + * + * This test checks child processes exit, meaning they don't hang like + * explained above. + */ + + + +// pipe echo | grep +echo.stdout.on('data', function(data) { + console.error('grep stdin write ' + data.length); + if (!grep.stdin.write(data)) { + echo.stdout.pause(); + } +}); + +grep.stdin.on('drain', function(data) { + echo.stdout.resume(); +}); + +// propagate end from echo to grep +echo.stdout.on('end', function(code) { + grep.stdin.end(); +}); + +echo.on('exit', function() { + console.error('echo exit'); +}); + +grep.on('exit', function() { + console.error('grep exit'); +}); + +sed.on('exit', function() { + console.error('sed exit'); +}); + + + +// pipe grep | sed +grep.stdout.on('data', function(data) { + console.error('grep stdout ' + data.length); + if (!sed.stdin.write(data)) { + grep.stdout.pause(); + } +}); + +sed.stdin.on('drain', function(data) { + grep.stdout.resume(); +}); + +// propagate end from grep to sed +grep.stdout.on('end', function(code) { + console.error('grep stdout end'); + sed.stdin.end(); +}); + + + +var result = ''; + +// print sed's output +sed.stdout.on('data', function(data) { + result += data.toString('utf8', 0, data.length); + util.print(data); +}); + +sed.stdout.on('end', function(code) { + assert.equal(result, 'hellO' + os.EOL + 'nOde' + os.EOL +'wOrld' + os.EOL); +}); diff --git a/test/parallel/test-child-process-env.js b/test/parallel/test-child-process-env.js new file mode 100644 index 000000000..caeb1936c --- /dev/null +++ b/test/parallel/test-child-process-env.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var isWindows = process.platform === 'win32'; + +var env = { + 'HELLO': 'WORLD' +}; +env.__proto__ = { + 'FOO': 'BAR' +}; + +if (isWindows) { + var child = spawn('cmd.exe', ['/c', 'set'], {env: env}); +} else { + var child = spawn('/usr/bin/env', [], {env: env}); +} + + +var response = ''; + +child.stdout.setEncoding('utf8'); + +child.stdout.on('data', function(chunk) { + console.log('stdout: ' + chunk); + response += chunk; +}); + +process.on('exit', function() { + assert.ok(response.indexOf('HELLO=WORLD') >= 0); + assert.ok(response.indexOf('FOO=BAR') >= 0); +}); diff --git a/test/parallel/test-child-process-exec-buffer.js b/test/parallel/test-child-process-exec-buffer.js new file mode 100644 index 000000000..937dce76e --- /dev/null +++ b/test/parallel/test-child-process-exec-buffer.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var os = require('os'); + +var success_count = 0; + +var str = 'hello'; + +// default encoding +var child = exec("echo " + str, function(err, stdout, stderr) { + assert.ok('string', typeof(stdout), 'Expected stdout to be a string'); + assert.ok('string', typeof(stderr), 'Expected stderr to be a string'); + assert.equal(str + os.EOL, stdout); + + success_count++; +}); + +// no encoding (Buffers expected) +var child = exec("echo " + str, { + encoding: null +}, function(err, stdout, stderr) { + assert.ok(stdout instanceof Buffer, 'Expected stdout to be a Buffer'); + assert.ok(stderr instanceof Buffer, 'Expected stderr to be a Buffer'); + assert.equal(str + os.EOL, stdout.toString()); + + success_count++; +}); + +process.on('exit', function() { + assert.equal(2, success_count); +}); diff --git a/test/parallel/test-child-process-exec-cwd.js b/test/parallel/test-child-process-exec-cwd.js new file mode 100644 index 000000000..282faec8b --- /dev/null +++ b/test/parallel/test-child-process-exec-cwd.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var success_count = 0; +var error_count = 0; + +var pwdcommand, dir; + +if (process.platform == 'win32') { + pwdcommand = 'echo %cd%'; + dir = 'c:\\windows'; +} else { + pwdcommand = 'pwd'; + dir = '/dev'; +} + +var child = exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { + if (err) { + error_count++; + console.log('error!: ' + err.code); + console.log('stdout: ' + JSON.stringify(stdout)); + console.log('stderr: ' + JSON.stringify(stderr)); + assert.equal(false, err.killed); + } else { + success_count++; + console.log(stdout); + assert.ok(stdout.indexOf(dir) == 0); + } +}); + +process.on('exit', function() { + assert.equal(1, success_count); + assert.equal(0, error_count); +}); diff --git a/test/parallel/test-child-process-exec-env.js b/test/parallel/test-child-process-exec-env.js new file mode 100644 index 000000000..b14ce741f --- /dev/null +++ b/test/parallel/test-child-process-exec-env.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var success_count = 0; +var error_count = 0; +var response = ''; +var child; + +function after(err, stdout, stderr) { + if (err) { + error_count++; + console.log('error!: ' + err.code); + console.log('stdout: ' + JSON.stringify(stdout)); + console.log('stderr: ' + JSON.stringify(stderr)); + assert.equal(false, err.killed); + } else { + success_count++; + assert.equal(true, stdout != ''); + } +} + +if (process.platform !== 'win32') { + child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after); +} else { + child = exec('set', { env: { 'HELLO': 'WORLD' } }, after); +} + +child.stdout.setEncoding('utf8'); +child.stdout.on('data', function(chunk) { + response += chunk; +}); + +process.on('exit', function() { + console.log('response: ', response); + assert.equal(1, success_count); + assert.equal(0, error_count); + assert.ok(response.indexOf('HELLO=WORLD') >= 0); +}); diff --git a/test/parallel/test-child-process-exec-error.js b/test/parallel/test-child-process-exec-error.js new file mode 100644 index 000000000..afe199764 --- /dev/null +++ b/test/parallel/test-child-process-exec-error.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var child_process = require('child_process'); + +function test(fun, code) { + var errors = 0; + + fun('does-not-exist', function(err) { + assert.equal(err.code, code); + assert(/does\-not\-exist/.test(err.cmd)); + errors++; + }); + + process.on('exit', function() { + assert.equal(errors, 1); + }); +} + +if (process.platform === 'win32') { + test(child_process.exec, 1); // exit code of cmd.exe +} else { + test(child_process.exec, 127); // exit code of /bin/sh +} + +test(child_process.execFile, 'ENOENT'); diff --git a/test/parallel/test-child-process-exit-code.js b/test/parallel/test-child-process-exit-code.js new file mode 100644 index 000000000..c0c25858b --- /dev/null +++ b/test/parallel/test-child-process-exit-code.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var path = require('path'); + +var exits = 0; + +var exitScript = path.join(common.fixturesDir, 'exit.js'); +var exitChild = spawn(process.argv[0], [exitScript, 23]); +exitChild.on('exit', function(code, signal) { + assert.strictEqual(code, 23); + assert.strictEqual(signal, null); + + exits++; +}); + + + +var errorScript = path.join(common.fixturesDir, + 'child_process_should_emit_error.js'); +var errorChild = spawn(process.argv[0], [errorScript]); +errorChild.on('exit', function(code, signal) { + assert.ok(code !== 0); + assert.strictEqual(signal, null); + + exits++; +}); + + +process.on('exit', function() { + assert.equal(2, exits); +}); diff --git a/test/parallel/test-child-process-fork-and-spawn.js b/test/parallel/test-child-process-fork-and-spawn.js new file mode 100644 index 000000000..989bf7ee3 --- /dev/null +++ b/test/parallel/test-child-process-fork-and-spawn.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var fork = require('child_process').fork; + +// Fork, then spawn. The spawned process should not hang. +switch (process.argv[2] || '') { +case '': + fork(__filename, ['fork']).on('exit', checkExit); + process.on('exit', haveExit); + break; +case 'fork': + spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); + process.on('exit', haveExit); + break; +case 'spawn': + break; +default: + assert(0); +} + +var seenExit = false; + +function checkExit(statusCode) { + seenExit = true; + assert.equal(statusCode, 0); + process.nextTick(process.exit); +} + +function haveExit() { + assert.equal(seenExit, true); +} diff --git a/test/parallel/test-child-process-fork-close.js b/test/parallel/test-child-process-fork-close.js new file mode 100644 index 000000000..342cffec3 --- /dev/null +++ b/test/parallel/test-child-process-fork-close.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + common = require('../common'), + fork = require('child_process').fork, + fork = require('child_process').fork; + +var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); + +var gotMessage = false, + gotExit = false, + gotClose = false; + +cp.on('message', function(message) { + assert(!gotMessage); + assert(!gotClose); + assert.strictEqual(message, 'hello'); + gotMessage = true; +}); + +cp.on('exit', function() { + assert(!gotExit); + assert(!gotClose); + gotExit = true; +}); + +cp.on('close', function() { + assert(gotMessage); + assert(gotExit); + assert(!gotClose); + gotClose = true; +}); + +process.on('exit', function() { + assert(gotMessage); + assert(gotExit); + assert(gotClose); +}); diff --git a/test/parallel/test-child-process-fork-dgram.js b/test/parallel/test-child-process-fork-dgram.js new file mode 100644 index 000000000..1c4e9acc3 --- /dev/null +++ b/test/parallel/test-child-process-fork-dgram.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * The purpose of this test is to make sure that when forking a process, + * sending a fd representing a UDP socket to the child and sending messages + * to this endpoint, these messages are distributed to the parent and the + * child process. + * + * Because it's not really possible to predict how the messages will be + * distributed among the parent and the child processes, we keep sending + * messages until both the parent and the child received at least one + * message. The worst case scenario is when either one never receives + * a message. In this case the test runner will timeout after 60 secs + * and the test will fail. + */ + +var dgram = require('dgram'); +var fork = require('child_process').fork; +var assert = require('assert'); +var common = require('../common'); + +if (process.platform === 'win32') { + console.error('Sending dgram sockets to child processes not supported'); + process.exit(0); +} + +if (process.argv[2] === 'child') { + var childCollected = 0; + var server; + + process.on('message', function removeMe(msg, clusterServer) { + if (msg === 'server') { + server = clusterServer; + + server.on('message', function () { + process.send('gotMessage'); + }); + + } else if (msg === 'stop') { + server.close(); + process.removeListener('message', removeMe); + } + }); + +} else { + var server = dgram.createSocket('udp4'); + var client = dgram.createSocket('udp4'); + var child = fork(__filename, ['child']); + + var msg = new Buffer('Some bytes'); + + var childGotMessage = false; + var parentGotMessage = false; + + server.on('message', function (msg, rinfo) { + parentGotMessage = true; + }); + + server.on('listening', function () { + child.send('server', server); + + child.once('message', function (msg) { + if (msg === 'gotMessage') { + childGotMessage = true; + } + }); + + sendMessages(); + }); + + var sendMessages = function () { + var timer = setInterval(function () { + client.send(msg, 0, msg.length, common.PORT, '127.0.0.1', function(err) { + if (err) throw err; + } + ); + + /* + * Both the parent and the child got at least one message, + * test passed, clean up everyting. + */ + if (parentGotMessage && childGotMessage) { + clearInterval(timer); + shutdown(); + } + + }, 1); + }; + + var shutdown = function () { + child.send('stop'); + + server.close(); + client.close(); + }; + + server.bind(common.PORT, '127.0.0.1'); + + process.once('exit', function () { + assert(parentGotMessage); + assert(childGotMessage); + }); +} diff --git a/test/parallel/test-child-process-fork-exec-argv.js b/test/parallel/test-child-process-fork-exec-argv.js new file mode 100644 index 000000000..d0da341c2 --- /dev/null +++ b/test/parallel/test-child-process-fork-exec-argv.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var child_process = require('child_process'); +var spawn = child_process.spawn; +var fork = child_process.fork; + +if (process.argv[2] === 'fork') { + process.stdout.write(JSON.stringify(process.execArgv), function() { + process.exit(); + }); +} else if (process.argv[2] === 'child') { + fork(__filename, ['fork']); +} else { + var execArgv = ['--harmony_proxies', '--stack-size=256']; + var args = [__filename, 'child', 'arg0']; + + var child = spawn(process.execPath, execArgv.concat(args)); + var out = ''; + + child.stdout.on('data', function (chunk) { + out += chunk; + }); + + child.on('exit', function () { + assert.deepEqual(JSON.parse(out), execArgv); + }); +} diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js new file mode 100755 index 000000000..e0cf77c28 --- /dev/null +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var cp = require('child_process'); +var fs = require('fs'); +var path = require('path'); +var common = require('../common'); +var msg = {test: 'this'}; +var nodePath = process.execPath; +var copyPath = path.join(common.tmpDir, 'node-copy.exe'); + +if (process.env.FORK) { + assert(process.send); + assert.equal(process.argv[0], copyPath); + process.send(msg); + process.exit(); +} +else { + try { + fs.unlinkSync(copyPath); + } + catch (e) { + if (e.code !== 'ENOENT') throw e; + } + fs.writeFileSync(copyPath, fs.readFileSync(nodePath)); + fs.chmodSync(copyPath, '0755'); + + // slow but simple + var envCopy = JSON.parse(JSON.stringify(process.env)); + envCopy.FORK = 'true'; + var child = require('child_process').fork(__filename, { + execPath: copyPath, + env: envCopy + }); + child.on('message', common.mustCall(function(recv) { + assert.deepEqual(msg, recv); + })); + child.on('exit', common.mustCall(function(code) { + fs.unlinkSync(copyPath); + assert.equal(code, 0); + })); +} diff --git a/test/parallel/test-child-process-fork-net.js b/test/parallel/test-child-process-fork-net.js new file mode 100644 index 000000000..feb2588fe --- /dev/null +++ b/test/parallel/test-child-process-fork-net.js @@ -0,0 +1,205 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); + +// progress tracker +function ProgressTracker(missing, callback) { + this.missing = missing; + this.callback = callback; +} +ProgressTracker.prototype.done = function() { + this.missing -= 1; + this.check(); +}; +ProgressTracker.prototype.check = function() { + if (this.missing === 0) this.callback(); +}; + +if (process.argv[2] === 'child') { + + var serverScope; + + process.on('message', function onServer(msg, server) { + if (msg.what !== 'server') return; + process.removeListener('message', onServer); + + serverScope = server; + + server.on('connection', function(socket) { + console.log('CHILD: got connection'); + process.send({what: 'connection'}); + socket.destroy(); + }); + + // start making connection from parent + console.log('CHILD: server listening'); + process.send({what: 'listening'}); + }); + + process.on('message', function onClose(msg) { + if (msg.what !== 'close') return; + process.removeListener('message', onClose); + + serverScope.on('close', function() { + process.send({what: 'close'}); + }); + serverScope.close(); + }); + + process.on('message', function onSocket(msg, socket) { + if (msg.what !== 'socket') return; + process.removeListener('message', onSocket); + socket.end('echo'); + console.log('CHILD: got socket'); + }); + + process.send({what: 'ready'}); +} else { + + var child = fork(process.argv[1], ['child']); + + child.on('exit', function() { + console.log('CHILD: died'); + }); + + // send net.Server to child and test by connecting + var testServer = function(callback) { + + // destroy server execute callback when done + var progress = new ProgressTracker(2, function() { + server.on('close', function() { + console.log('PARENT: server closed'); + child.send({what: 'close'}); + }); + server.close(); + }); + + // we expect 10 connections and close events + var connections = new ProgressTracker(10, progress.done.bind(progress)); + var closed = new ProgressTracker(10, progress.done.bind(progress)); + + // create server and send it to child + var server = net.createServer(); + server.on('connection', function(socket) { + console.log('PARENT: got connection'); + socket.destroy(); + connections.done(); + }); + server.on('listening', function() { + console.log('PARENT: server listening'); + child.send({what: 'server'}, server); + }); + server.listen(common.PORT); + + // handle client messages + var messageHandlers = function(msg) { + + if (msg.what === 'listening') { + // make connections + var socket; + for (var i = 0; i < 10; i++) { + socket = net.connect(common.PORT, function() { + console.log('CLIENT: connected'); + }); + socket.on('close', function() { + closed.done(); + console.log('CLIENT: closed'); + }); + } + + } else if (msg.what === 'connection') { + // child got connection + connections.done(); + } else if (msg.what === 'close') { + child.removeListener('message', messageHandlers); + callback(); + } + }; + + child.on('message', messageHandlers); + }; + + // send net.Socket to child + var testSocket = function(callback) { + + // create a new server and connect to it, + // but the socket will be handled by the child + var server = net.createServer(); + server.on('connection', function(socket) { + socket.on('close', function() { + console.log('CLIENT: socket closed'); + }); + child.send({what: 'socket'}, socket); + }); + server.on('close', function() { + console.log('PARENT: server closed'); + callback(); + }); + // don't listen on the same port, because SmartOS sometimes says + // that the server's fd is closed, but it still cannot listen + // on the same port again. + // + // An isolated test for this would be lovely, but for now, this + // will have to do. + server.listen(common.PORT + 1, function() { + console.error('testSocket, listening'); + var connect = net.connect(common.PORT + 1); + var store = ''; + connect.on('data', function(chunk) { + store += chunk; + console.log('CLIENT: got data'); + }); + connect.on('close', function() { + console.log('CLIENT: closed'); + assert.equal(store, 'echo'); + server.close(); + }); + }); + }; + + // create server and send it to child + var serverSuccess = false; + var socketSuccess = false; + child.on('message', function onReady(msg) { + if (msg.what !== 'ready') return; + child.removeListener('message', onReady); + + testServer(function() { + serverSuccess = true; + + testSocket(function() { + socketSuccess = true; + child.kill(); + }); + }); + + }); + + process.on('exit', function() { + assert.ok(serverSuccess); + assert.ok(socketSuccess); + }); + +} diff --git a/test/parallel/test-child-process-fork-net2.js b/test/parallel/test-child-process-fork-net2.js new file mode 100644 index 000000000..098870d48 --- /dev/null +++ b/test/parallel/test-child-process-fork-net2.js @@ -0,0 +1,180 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); +var count = 12; + +if (process.argv[2] === 'child') { + var needEnd = []; + var id = process.argv[3]; + + process.on('message', function(m, socket) { + if (!socket) return; + + console.error('[%d] got socket', id, m); + + // will call .end('end') or .write('write'); + socket[m](m); + + socket.resume(); + + socket.on('data', function() { + console.error('[%d] socket.data', id, m); + }); + + socket.on('end', function() { + console.error('[%d] socket.end', id, m); + }); + + // store the unfinished socket + if (m === 'write') { + needEnd.push(socket); + } + + socket.on('close', function(had_error) { + console.error('[%d] socket.close', id, had_error, m); + }); + + socket.on('finish', function() { + console.error('[%d] socket finished', id, m); + }); + }); + + process.on('message', function(m) { + if (m !== 'close') return; + console.error('[%d] got close message', id); + needEnd.forEach(function(endMe, i) { + console.error('[%d] ending %d/%d', id, i, needEnd.length); + endMe.end('end'); + }); + }); + + process.on('disconnect', function() { + console.error('[%d] process disconnect, ending', id); + needEnd.forEach(function(endMe, i) { + console.error('[%d] ending %d/%d', id, i, needEnd.length); + endMe.end('end'); + }); + }); + +} else { + + var child1 = fork(process.argv[1], ['child', '1']); + var child2 = fork(process.argv[1], ['child', '2']); + var child3 = fork(process.argv[1], ['child', '3']); + + var server = net.createServer(); + + var connected = 0, + closed = 0; + server.on('connection', function(socket) { + switch (connected % 6) { + case 0: + child1.send('end', socket, { track: false }); break; + case 1: + child1.send('write', socket, { track: true }); break; + case 2: + child2.send('end', socket, { track: true }); break; + case 3: + child2.send('write', socket, { track: false }); break; + case 4: + child3.send('end', socket, { track: false }); break; + case 5: + child3.send('write', socket, { track: false }); break; + } + connected += 1; + + socket.once('close', function() { + console.log('[m] socket closed, total %d', ++closed); + }); + + if (connected === count) { + closeServer(); + } + }); + + var disconnected = 0; + server.on('listening', function() { + + var j = count, client; + while (j--) { + client = net.connect(common.PORT, '127.0.0.1'); + client.on('error', function() { + // This can happen if we kill the child too early. + // The client should still get a close event afterwards. + console.error('[m] CLIENT: error event'); + }); + client.on('close', function() { + console.error('[m] CLIENT: close event'); + disconnected += 1; + }); + // XXX This resume() should be unnecessary. + // a stream high water mark should be enough to keep + // consuming the input. + client.resume(); + } + }); + + var closeEmitted = false; + server.on('close', function() { + console.error('[m] server close'); + closeEmitted = true; + + console.error('[m] killing child processes'); + child1.kill(); + child2.kill(); + child3.kill(); + }); + + server.listen(common.PORT, '127.0.0.1'); + + var timeElasped = 0; + var closeServer = function() { + console.error('[m] closeServer'); + var startTime = Date.now(); + server.on('close', function() { + console.error('[m] emit(close)'); + timeElasped = Date.now() - startTime; + }); + + console.error('[m] calling server.close'); + server.close(); + + setTimeout(function() { + assert(!closeEmitted); + console.error('[m] sending close to children'); + child1.send('close'); + child2.send('close'); + child3.disconnect(); + }, 200); + }; + + process.on('exit', function() { + assert.equal(disconnected, count); + assert.equal(connected, count); + assert.ok(closeEmitted); + assert.ok(timeElasped >= 190 && timeElasped <= 1000, + 'timeElasped was not between 190 and 1000 ms'); + }); +} diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js new file mode 100644 index 000000000..21954ec73 --- /dev/null +++ b/test/parallel/test-child-process-fork-ref.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fork = require('child_process').fork; + +if (process.argv[2] === 'child') { + process.send('1'); + + // check that child don't instantly die + setTimeout(function() { + process.send('2'); + }, 200); + + process.on('disconnect', function () { + process.stdout.write('3'); + }); + +} else { + var child = fork(__filename, ['child'], {silent: true}); + + var ipc = [], stdout = ''; + + child.on('message', function (msg) { + ipc.push(msg); + + if (msg === '2') child.disconnect(); + }); + + child.stdout.on('data', function (chunk) { + stdout += chunk; + }); + + child.once('exit', function () { + assert.deepEqual(ipc, ['1', '2']); + assert.equal(stdout, '3'); + }); +} diff --git a/test/parallel/test-child-process-fork-ref2.js b/test/parallel/test-child-process-fork-ref2.js new file mode 100644 index 000000000..3d604142b --- /dev/null +++ b/test/parallel/test-child-process-fork-ref2.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fork = require('child_process').fork; + +if (process.argv[2] === 'child') { + console.log('child -> call disconnect'); + process.disconnect(); + + setTimeout(function() { + console.log('child -> will this keep it alive?'); + process.on('message', function () { }); + }, 400); + +} else { + var child = fork(__filename, ['child']); + + child.on('disconnect', function () { + console.log('parent -> disconnect'); + }); + + child.once('exit', function () { + console.log('parent -> exit'); + }); +} diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js new file mode 100644 index 000000000..41cc28c72 --- /dev/null +++ b/test/parallel/test-child-process-fork.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var args = ['foo', 'bar']; + +var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); +assert.deepEqual(args, ['foo', 'bar']); + +var messageCount = 0; + +n.on('message', function(m) { + console.log('PARENT got message:', m); + assert.ok(m.foo); + messageCount++; +}); + +// https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) +// returns "undefined" but JSON.parse() cannot parse that... +assert.throws(function() { n.send(undefined); }, TypeError); +assert.throws(function() { n.send(); }, TypeError); + +n.send({ hello: 'world' }); + +var childExitCode = -1; +n.on('exit', function(c) { + childExitCode = c; +}); + +process.on('exit', function() { + assert.ok(childExitCode == 0); +}); diff --git a/test/parallel/test-child-process-fork3.js b/test/parallel/test-child-process-fork3.js new file mode 100644 index 000000000..0f75b029e --- /dev/null +++ b/test/parallel/test-child-process-fork3.js @@ -0,0 +1,25 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var child_process = require('child_process'); + +child_process.fork(common.fixturesDir + '/empty.js'); // should not hang diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js new file mode 100644 index 000000000..dd7ce556b --- /dev/null +++ b/test/parallel/test-child-process-internal.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +//messages +var PREFIX = 'NODE_'; +var normal = {cmd: 'foo' + PREFIX}; +var internal = {cmd: PREFIX + 'bar'}; + +if (process.argv[2] === 'child') { + //send non-internal message containing PREFIX at a non prefix position + process.send(normal); + + //send inernal message + process.send(internal); + + process.exit(0); + +} else { + + var fork = require('child_process').fork; + var child = fork(process.argv[1], ['child']); + + var gotNormal; + child.once('message', function(data) { + gotNormal = data; + }); + + var gotInternal; + child.once('internalMessage', function(data) { + gotInternal = data; + }); + + process.on('exit', function() { + assert.deepEqual(gotNormal, normal); + assert.deepEqual(gotInternal, internal); + }); +} diff --git a/test/parallel/test-child-process-ipc.js b/test/parallel/test-child-process-ipc.js new file mode 100644 index 000000000..e8144e439 --- /dev/null +++ b/test/parallel/test-child-process-ipc.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var path = require('path'); + +var sub = path.join(common.fixturesDir, 'echo.js'); + +var gotHelloWorld = false; +var gotEcho = false; + +var child = spawn(process.argv[0], [sub]); + +child.stderr.on('data', function(data) { + console.log('parent stderr: ' + data); +}); + +child.stdout.setEncoding('utf8'); + +child.stdout.on('data', function(data) { + console.log('child said: ' + JSON.stringify(data)); + if (!gotHelloWorld) { + console.error('testing for hello world'); + assert.equal('hello world\r\n', data); + gotHelloWorld = true; + console.error('writing echo me'); + child.stdin.write('echo me\r\n'); + } else { + console.error('testing for echo me'); + assert.equal('echo me\r\n', data); + gotEcho = true; + child.stdin.end(); + } +}); + +child.stdout.on('end', function(data) { + console.log('child end'); +}); + + +process.on('exit', function() { + assert.ok(gotHelloWorld); + assert.ok(gotEcho); +}); diff --git a/test/parallel/test-child-process-kill.js b/test/parallel/test-child-process-kill.js new file mode 100644 index 000000000..08a0185d3 --- /dev/null +++ b/test/parallel/test-child-process-kill.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +var is_windows = process.platform === 'win32'; + +var exitCode; +var termSignal; +var gotStdoutEOF = false; +var gotStderrEOF = false; + +var cat = spawn(is_windows ? 'cmd' : 'cat'); + + +cat.stdout.on('end', function() { + gotStdoutEOF = true; +}); + +cat.stderr.on('data', function(chunk) { + assert.ok(false); +}); + +cat.stderr.on('end', function() { + gotStderrEOF = true; +}); + +cat.on('exit', function(code, signal) { + exitCode = code; + termSignal = signal; +}); + +assert.equal(cat.killed, false); +cat.kill(); +assert.equal(cat.killed, true); + +process.on('exit', function() { + assert.strictEqual(exitCode, null); + assert.strictEqual(termSignal, 'SIGTERM'); + assert.ok(gotStdoutEOF); + assert.ok(gotStderrEOF); +}); diff --git a/test/parallel/test-child-process-recv-handle.js b/test/parallel/test-child-process-recv-handle.js new file mode 100644 index 000000000..dce5bdcba --- /dev/null +++ b/test/parallel/test-child-process-recv-handle.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Test that a Linux specific quirk in the handle passing protocol is handled +// correctly. See https://github.com/joyent/node/issues/5330 for details. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var spawn = require('child_process').spawn; + +if (process.argv[2] === 'worker') + worker(); +else + master(); + +function master() { + // spawn() can only create one IPC channel so we use stdin/stdout as an + // ad-hoc command channel. + var proc = spawn(process.execPath, [__filename, 'worker'], { + stdio: ['pipe', 'pipe', 'pipe', 'ipc'] + }); + var handle = null; + proc.on('exit', function() { + handle.close(); + }); + proc.stdout.on('data', function(data) { + assert.equal(data, 'ok\r\n'); + net.createServer(assert.fail).listen(common.PORT, function() { + handle = this._handle; + proc.send('one'); + proc.send('two', handle); + proc.send('three'); + proc.stdin.write('ok\r\n'); + }); + }); + proc.stderr.pipe(process.stderr); +} + +function worker() { + process._channel.readStop(); // Make messages batch up. + process.stdout.ref(); + process.stdout.write('ok\r\n'); + process.stdin.once('data', function(data) { + assert.equal(data, 'ok\r\n'); + process._channel.readStart(); + }); + var n = 0; + process.on('message', function(msg, handle) { + n += 1; + if (n === 1) { + assert.equal(msg, 'one'); + assert.equal(handle, undefined); + } + else if (n === 2) { + assert.equal(msg, 'two'); + assert.equal(typeof handle, 'object'); // Also matches null, therefore... + assert.ok(handle); // also check that it's truthy. + handle.close(); + } + else if (n === 3) { + assert.equal(msg, 'three'); + assert.equal(handle, undefined); + process.exit(); + } + }); +} diff --git a/test/parallel/test-child-process-send-utf8.js b/test/parallel/test-child-process-send-utf8.js new file mode 100644 index 000000000..b3ce24390 --- /dev/null +++ b/test/parallel/test-child-process-send-utf8.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fork = require('child_process').fork; + +var expected = Array(1e5).join('ßßßß'); +if (process.argv[2] === 'child') { + process.send(expected); +} else { + var child = fork(process.argv[1], ['child']); + child.on('message', common.mustCall(function(actual) { + assert.equal(actual, expected); + })); +} diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js new file mode 100644 index 000000000..e07c6cc4d --- /dev/null +++ b/test/parallel/test-child-process-set-blocking.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var ch = require('child_process'); + +var SIZE = 100000; +var childGone = false; + +var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { + stdio: 'inherit' +}); + +cp.on('exit', function(code) { + childGone = true; + assert.equal(0, code); +}); + +process.on('exit', function() { + assert.ok(childGone); +}); diff --git a/test/parallel/test-child-process-silent.js b/test/parallel/test-child-process-silent.js new file mode 100644 index 000000000..e34daa3a8 --- /dev/null +++ b/test/parallel/test-child-process-silent.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var childProcess = require('child_process'); + +// Child pipe test +if (process.argv[2] === 'pipetest') { + process.stdout.write('stdout message'); + process.stderr.write('stderr message'); + +} else if (process.argv[2] === 'ipctest') { + // Child IPC test + process.send('message from child'); + process.on('message', function() { + process.send('got message from master'); + }); + +} else if (process.argv[2] === 'parent') { + // Parent | start child pipe test + + var child = childProcess.fork(process.argv[1], ['pipetest'], {silent: true}); + + // Allow child process to self terminate + child._channel.close(); + child._channel = null; + + child.on('exit', function() { + process.exit(0); + }); + +} else { + // testcase | start parent && child IPC test + + // testing: is stderr and stdout piped to parent + var args = [process.argv[1], 'parent']; + var parent = childProcess.spawn(process.execPath, args); + + //got any stderr or std data + var stdoutData = false; + parent.stdout.on('data', function() { + stdoutData = true; + }); + var stderrData = false; + parent.stdout.on('data', function() { + stderrData = true; + }); + + // testing: do message system work when using silent + var child = childProcess.fork(process.argv[1], ['ipctest'], {silent: true}); + + // Manual pipe so we will get errors + child.stderr.pipe(process.stderr, {end: false}); + child.stdout.pipe(process.stdout, {end: false}); + + var childSending = false; + var childReciveing = false; + child.on('message', function(message) { + if (childSending === false) { + childSending = (message === 'message from child'); + } + + if (childReciveing === false) { + childReciveing = (message === 'got message from master'); + } + + if (childReciveing === true) { + child.kill(); + } + }); + child.send('message to child'); + + // Check all values + process.on('exit', function() { + // clean up + child.kill(); + parent.kill(); + + // Check std(out|err) pipes + assert.ok(!stdoutData, 'The stdout socket was piped to parent'); + assert.ok(!stderrData, 'The stderr socket was piped to parent'); + + // Check message system + assert.ok(childSending, 'The child was able to send a message'); + assert.ok(childReciveing, 'The child was able to receive a message'); + }); +} diff --git a/test/parallel/test-child-process-spawn-error.js b/test/parallel/test-child-process-spawn-error.js new file mode 100644 index 000000000..5ecfbff26 --- /dev/null +++ b/test/parallel/test-child-process-spawn-error.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); +var spawn = require('child_process').spawn; +var assert = require('assert'); + +var errors = 0; + +var enoentPath = 'foo123'; +assert.equal(fs.existsSync(enoentPath), false); + +var enoentChild = spawn(enoentPath); +enoentChild.on('error', function (err) { + assert.equal(err.path, enoentPath); + errors++; +}); + +process.on('exit', function() { + assert.equal(1, errors); +}); diff --git a/test/parallel/test-child-process-spawn-typeerror.js b/test/parallel/test-child-process-spawn-typeerror.js new file mode 100644 index 000000000..4fd360a3f --- /dev/null +++ b/test/parallel/test-child-process-spawn-typeerror.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var spawn = require('child_process').spawn, + assert = require('assert'), + windows = (process.platform === 'win32'), + cmd = (windows) ? 'rundll32' : 'ls', + invalidcmd = 'hopefully_you_dont_have_this_on_your_machine', + invalidArgsMsg = /Incorrect value of args option/, + invalidOptionsMsg = /options argument must be an object/, + errors = 0; + +try { + // Ensure this throws a TypeError + var child = spawn(invalidcmd, 'this is not an array'); + + child.on('error', function (err) { + errors++; + }); + +} catch (e) { + assert.equal(e instanceof TypeError, true); +} + +// verify that valid argument combinations do not throw +assert.doesNotThrow(function() { + spawn(cmd); +}); + +assert.doesNotThrow(function() { + spawn(cmd, []); +}); + +assert.doesNotThrow(function() { + spawn(cmd, {}); +}); + +assert.doesNotThrow(function() { + spawn(cmd, [], {}); +}); + +// verify that invalid argument combinations throw +assert.throws(function() { + spawn(); +}, /Bad argument/); + +assert.throws(function() { + spawn(cmd, null); +}, invalidArgsMsg); + +assert.throws(function() { + spawn(cmd, true); +}, invalidArgsMsg); + +assert.throws(function() { + spawn(cmd, [], null); +}, invalidOptionsMsg); + +assert.throws(function() { + spawn(cmd, [], 1); +}, invalidOptionsMsg); + +process.on('exit', function() { + assert.equal(errors, 0); +}); diff --git a/test/parallel/test-child-process-spawnsync-env.js b/test/parallel/test-child-process-spawnsync-env.js new file mode 100644 index 000000000..0cde9ffee --- /dev/null +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cp = require('child_process'); + +if (process.argv[2] === 'child') { + console.log(process.env.foo); +} else { + var expected = 'bar'; + var child = cp.spawnSync(process.execPath, [__filename, 'child'], { + env: {foo: expected} + }); + + assert.equal(child.stdout.toString().trim(), expected); +} diff --git a/test/parallel/test-child-process-spawnsync-input.js b/test/parallel/test-child-process-spawnsync-input.js new file mode 100644 index 000000000..66b2fa354 --- /dev/null +++ b/test/parallel/test-child-process-spawnsync-input.js @@ -0,0 +1,119 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var os = require('os'); +var util = require('util'); + +var spawnSync = require('child_process').spawnSync; + +var msgOut = 'this is stdout'; +var msgErr = 'this is stderr'; + +// this is actually not os.EOL? +var msgOutBuf = new Buffer(msgOut + '\n'); +var msgErrBuf = new Buffer(msgErr + '\n'); + +var args = [ + '-e', + util.format('console.log("%s"); console.error("%s");', msgOut, msgErr) +]; + +var ret; + + +if (process.argv.indexOf('spawnchild') !== -1) { + switch (process.argv[3]) { + case '1': + ret = spawnSync(process.execPath, args, { stdio: 'inherit' }); + common.checkSpawnSyncRet(ret); + break; + case '2': + ret = spawnSync(process.execPath, args, { + stdio: ['inherit', 'inherit', 'inherit'] + }); + common.checkSpawnSyncRet(ret); + break; + } + process.exit(0); + return; +} + + +function verifyBufOutput(ret) { + common.checkSpawnSyncRet(ret); + assert.deepEqual(ret.stdout, msgOutBuf); + assert.deepEqual(ret.stderr, msgErrBuf); +} + + +verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 1])); +verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 2])); + +var options = { + input: 1234 +}; + +assert.throws(function() { + spawnSync('cat', [], options); +}, /TypeError:.*should be Buffer or string not number/); + + +options = { + input: 'hello world' +}; + +ret = spawnSync('cat', [], options); + +common.checkSpawnSyncRet(ret); +assert.strictEqual(ret.stdout.toString('utf8'), options.input); +assert.strictEqual(ret.stderr.toString('utf8'), ''); + +options = { + input: new Buffer('hello world') +}; + +ret = spawnSync('cat', [], options); + +common.checkSpawnSyncRet(ret); +assert.deepEqual(ret.stdout, options.input); +assert.deepEqual(ret.stderr, new Buffer('')); + +verifyBufOutput(spawnSync(process.execPath, args)); + +ret = spawnSync(process.execPath, args, { encoding: 'utf8' }); + +common.checkSpawnSyncRet(ret); +assert.strictEqual(ret.stdout, msgOut + '\n'); +assert.strictEqual(ret.stderr, msgErr + '\n'); + +options = { + maxBuffer: 1 +}; + +ret = spawnSync(process.execPath, args, options); + +assert.ok(ret.error, 'maxBuffer should error'); +assert.strictEqual(ret.error.errno, 'ENOBUFS'); +// we can have buffers larger than maxBuffer because underneath we alloc 64k +// that matches our read sizes +assert.deepEqual(ret.stdout, msgOutBuf); diff --git a/test/parallel/test-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js new file mode 100644 index 000000000..691f58786 --- /dev/null +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawnSync = require('child_process').spawnSync; + +var TIMER = 200; +var SLEEP = 1000; + +switch (process.argv[2]) { + case 'child': + setTimeout(function() { + console.log('child fired'); + process.exit(1); + }, SLEEP); + break; + default: + var start = Date.now(); + var ret = spawnSync(process.execPath, [__filename, 'child'], {timeout: TIMER}); + assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); + console.log(ret); + var end = Date.now() - start; + assert(end < SLEEP); + assert(ret.status > 128 || ret.signal); + break; +} diff --git a/test/parallel/test-child-process-spawnsync.js b/test/parallel/test-child-process-spawnsync.js new file mode 100644 index 000000000..a7cbb8d1d --- /dev/null +++ b/test/parallel/test-child-process-spawnsync.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawnSync = require('child_process').spawnSync; + +var TIMER = 100; +var SLEEP = 1000; + +var timeout = 0; + +setTimeout(function() { + timeout = process.hrtime(start); + assert.ok(stop, 'timer should not fire before process exits'); + assert.strictEqual(timeout[0], 1, 'timer should take as long as sleep'); +}, TIMER); + +console.log('sleep started'); +var start = process.hrtime(); +var ret = spawnSync('sleep', ['1']); +var stop = process.hrtime(start); +assert.strictEqual(ret.status, 0, 'exit status should be zero'); +console.log('sleep exited', stop); +assert.strictEqual(stop[0], 1, 'sleep should not take longer or less than 1 second'); + +// Error test when command does not exist +var ret_err = spawnSync('command_does_not_exist'); +assert.strictEqual(ret_err.error.code, 'ENOENT'); + +// Verify that the cwd option works - GH #7824 +(function() { + var response; + var cwd; + + if (process.platform === 'win32') { + cwd = 'c:\\'; + response = spawnSync('cmd.exe', ['/c', 'cd'], {cwd: cwd}); + } else { + cwd = '/'; + response = spawnSync('pwd', [], {cwd: cwd}); + } + + assert.strictEqual(response.stdout.toString().trim(), cwd); +})(); diff --git a/test/parallel/test-child-process-stdin-ipc.js b/test/parallel/test-child-process-stdin-ipc.js new file mode 100644 index 000000000..cd6a921d0 --- /dev/null +++ b/test/parallel/test-child-process-stdin-ipc.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; + +if (process.argv[2] === 'child') { + // Just reference stdin, it should start it + process.stdin; + return; +} + +var proc = spawn(process.execPath, [__filename, 'child'], { + stdio: ['ipc', 'inherit', 'inherit'] +}); + +var childCode = -1; +proc.on('exit', function(code) { + childCode = code; +}); + +process.on('exit', function() { + assert.equal(childCode, 0); +}); diff --git a/test/parallel/test-child-process-stdin.js b/test/parallel/test-child-process-stdin.js new file mode 100644 index 000000000..fdb40cc82 --- /dev/null +++ b/test/parallel/test-child-process-stdin.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; +var is_windows = process.platform === 'win32'; + +var cat = spawn(is_windows ? 'more' : 'cat'); +cat.stdin.write('hello'); +cat.stdin.write(' '); +cat.stdin.write('world'); + +assert.ok(cat.stdin.writable); +assert.ok(!cat.stdin.readable); + +cat.stdin.end(); + +var response = ''; +var exitStatus = -1; +var closed = false; + +var gotStdoutEOF = false; + +cat.stdout.setEncoding('utf8'); +cat.stdout.on('data', function(chunk) { + console.log('stdout: ' + chunk); + response += chunk; +}); + +cat.stdout.on('end', function() { + gotStdoutEOF = true; +}); + + +var gotStderrEOF = false; + +cat.stderr.on('data', function(chunk) { + // shouldn't get any stderr output + assert.ok(false); +}); + +cat.stderr.on('end', function(chunk) { + gotStderrEOF = true; +}); + + +cat.on('exit', function(status) { + console.log('exit event'); + exitStatus = status; +}); + +cat.on('close', function () { + closed = true; + if (is_windows) { + assert.equal('hello world\r\n', response); + } else { + assert.equal('hello world', response); + } +}); + +process.on('exit', function() { + assert.equal(0, exitStatus); + assert(closed); + if (is_windows) { + assert.equal('hello world\r\n', response); + } else { + assert.equal('hello world', response); + } +}); diff --git a/test/parallel/test-child-process-stdio-big-write-end.js b/test/parallel/test-child-process-stdio-big-write-end.js new file mode 100644 index 000000000..845a23e66 --- /dev/null +++ b/test/parallel/test-child-process-stdio-big-write-end.js @@ -0,0 +1,79 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var BUFSIZE = 1024; + +switch (process.argv[2]) { + case undefined: + return parent(); + case 'child': + return child(); + default: + throw new Error('wtf?'); +} + +function parent() { + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child']); + var sent = 0; + + var n = ''; + child.stdout.setEncoding('ascii'); + child.stdout.on('data', function(c) { + n += c; + }); + child.stdout.on('end', function() { + assert.equal(+n, sent); + console.log('ok'); + }); + + // Write until the buffer fills up. + do { + var buf = new Buffer(BUFSIZE); + buf.fill('.'); + sent += BUFSIZE; + } while (child.stdin.write(buf)); + + // then write a bunch more times. + for (var i = 0; i < 100; i++) { + var buf = new Buffer(BUFSIZE); + buf.fill('.'); + sent += BUFSIZE; + child.stdin.write(buf); + } + + // now end, before it's all flushed. + child.stdin.end(); + + // now we wait... +} + +function child() { + var received = 0; + process.stdin.on('data', function(c) { + received += c.length; + }); + process.stdin.on('end', function() { + console.log(received); + }); +} diff --git a/test/parallel/test-child-process-stdio-inherit.js b/test/parallel/test-child-process-stdio-inherit.js new file mode 100644 index 000000000..f7776fecb --- /dev/null +++ b/test/parallel/test-child-process-stdio-inherit.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +if (process.argv[2] === 'parent') + parent(); +else + grandparent(); + +function grandparent() { + var child = spawn(process.execPath, [__filename, 'parent']); + child.stderr.pipe(process.stderr); + var output = ''; + var input = 'asdfasdf'; + + child.stdout.on('data', function(chunk) { + output += chunk; + }); + child.stdout.setEncoding('utf8'); + + child.stdin.end(input); + + child.on('close', function(code, signal) { + assert.equal(code, 0); + assert.equal(signal, null); + // cat on windows adds a \r\n at the end. + assert.equal(output.trim(), input.trim()); + }); +} + +function parent() { + // should not immediately exit. + var child = common.spawnCat({ stdio: 'inherit' }); +} diff --git a/test/parallel/test-child-process-stdio.js b/test/parallel/test-child-process-stdio.js new file mode 100644 index 000000000..32da15f5f --- /dev/null +++ b/test/parallel/test-child-process-stdio.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var options = {stdio: ['pipe']}; +var child = common.spawnPwd(options); + +assert.notEqual(child.stdout, null); +assert.notEqual(child.stderr, null); + +options = {stdio: 'ignore'}; +child = common.spawnPwd(options); + +assert.equal(child.stdout, null); +assert.equal(child.stderr, null); diff --git a/test/parallel/test-child-process-stdout-flush-exit.js b/test/parallel/test-child-process-stdout-flush-exit.js new file mode 100644 index 000000000..49a0ec0e5 --- /dev/null +++ b/test/parallel/test-child-process-stdout-flush-exit.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); + +// if child process output to console and exit +if (process.argv[2] === 'child') { + console.log('hello'); + for (var i = 0; i < 200; i++) { + console.log('filler'); + } + console.log('goodbye'); + process.exit(0); +} else { + // parent process + var spawn = require('child_process').spawn; + + // spawn self as child + var child = spawn(process.argv[0], [process.argv[1], 'child']); + + var gotHello = false; + var gotBye = false; + + child.stderr.setEncoding('utf8'); + child.stderr.on('data', function (data) { + console.log('parent stderr: ' + data); + assert.ok(false); + }); + + // check if we receive both 'hello' at start and 'goodbye' at end + child.stdout.setEncoding('utf8'); + child.stdout.on('data', function (data) { + if (data.slice(0, 6) == 'hello\n') { + gotHello = true; + } else if (data.slice(data.length - 8) == 'goodbye\n') { + gotBye = true; + } else { + gotBye = false; + } + }); + + child.on('close', function (data) { + assert(gotHello); + assert(gotBye); + }); +} diff --git a/test/parallel/test-child-process-stdout-flush.js b/test/parallel/test-child-process-stdout-flush.js new file mode 100644 index 000000000..adb33f5c0 --- /dev/null +++ b/test/parallel/test-child-process-stdout-flush.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var spawn = require('child_process').spawn; +var sub = path.join(common.fixturesDir, 'print-chars.js'); + +var n = 500000; + +var child = spawn(process.argv[0], [sub, n]); + +var count = 0; + +child.stderr.setEncoding('utf8'); +child.stderr.on('data', function(data) { + console.log('parent stderr: ' + data); + assert.ok(false); +}); + +child.stdout.setEncoding('utf8'); +child.stdout.on('data', function(data) { + count += data.length; + console.log(count); +}); + +child.on('close', function(data) { + assert.equal(n, count); + console.log('okay'); +}); diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js new file mode 100644 index 000000000..d055ad5e3 --- /dev/null +++ b/test/parallel/test-cli-eval.js @@ -0,0 +1,97 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (module.parent) { + // signal we've been loaded as a module + console.log('Loaded as a module, exiting with status code 42.'); + process.exit(42); +} + +var common = require('../common.js'), + assert = require('assert'), + child = require('child_process'), + nodejs = '"' + process.execPath + '"'; + + +// replace \ by / because windows uses backslashes in paths, but they're still +// interpreted as the escape character when put between quotes. +var filename = __filename.replace(/\\/g, '/'); + +// assert that nothing is written to stdout +child.exec(nodejs + ' --eval 42', + function(err, stdout, stderr) { + assert.equal(stdout, ''); + assert.equal(stderr, ''); + }); + +// assert that "42\n" is written to stderr +child.exec(nodejs + ' --eval "console.error(42)"', + function(err, stdout, stderr) { + assert.equal(stdout, ''); + assert.equal(stderr, '42\n'); + }); + +// assert that the expected output is written to stdout +['--print', '-p -e', '-pe', '-p'].forEach(function(s) { + var cmd = nodejs + ' ' + s + ' '; + + child.exec(cmd + '42', + function(err, stdout, stderr) { + assert.equal(stdout, '42\n'); + assert.equal(stderr, ''); + }); + + child.exec(cmd + "'[]'", + function(err, stdout, stderr) { + assert.equal(stdout, '[]\n'); + assert.equal(stderr, ''); + }); +}); + +// assert that module loading works +child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', + function(status, stdout, stderr) { + assert.equal(status.code, 42); + }); + +// module path resolve bug, regression test +child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"', + function(status, stdout, stderr) { + assert.equal(status.code, 42); + }); + +// empty program should do nothing +child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { + assert.equal(stdout, ''); + assert.equal(stderr, ''); +}); + +// "\\-42" should be interpreted as an escaped expression, not a switch +child.exec(nodejs + ' -p "\\-42"', + function(err, stdout, stderr) { + assert.equal(stdout, '-42\n'); + assert.equal(stderr, ''); + }); + +child.exec(nodejs + ' --use-strict -p process.execArgv', + function(status, stdout, stderr) { + assert.equal(stdout, "[ '--use-strict', '-p', 'process.execArgv' ]\n"); + }); diff --git a/test/parallel/test-cluster-basic.js b/test/parallel/test-cluster-basic.js new file mode 100644 index 000000000..e6adfb5ba --- /dev/null +++ b/test/parallel/test-cluster-basic.js @@ -0,0 +1,183 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +assert.equal('NODE_UNIQUE_ID' in process.env, false, + 'NODE_UNIQUE_ID should be removed on startup'); + +function forEach(obj, fn) { + Object.keys(obj).forEach(function(name, index) { + fn(obj[name], name, index); + }); +} + + +if (cluster.isWorker) { + var http = require('http'); + http.Server(function() { + + }).listen(common.PORT, '127.0.0.1'); +} + +else if (cluster.isMaster) { + + var checks = { + cluster: { + events: { + fork: false, + online: false, + listening: false, + exit: false + }, + equal: { + fork: false, + online: false, + listening: false, + exit: false + } + }, + + worker: { + events: { + online: false, + listening: false, + exit: false + }, + equal: { + online: false, + listening: false, + exit: false + }, + states: { + none: false, + online: false, + listening: false, + dead: false + } + } + }; + + var worker; + var stateNames = Object.keys(checks.worker.states); + + //Check events, states, and emit arguments + forEach(checks.cluster.events, function(bool, name, index) { + + //Listen on event + cluster.on(name, function(/* worker */) { + + //Set event + checks.cluster.events[name] = true; + + //Check argument + checks.cluster.equal[name] = worker === arguments[0]; + + //Check state + var state = stateNames[index]; + checks.worker.states[state] = (state === worker.state); + }); + }); + + //Kill worker when listening + cluster.on('listening', function() { + worker.kill(); + }); + + //Kill process when worker is killed + cluster.on('exit', function() { + process.exit(0); + }); + + //Create worker + worker = cluster.fork(); + assert.equal(worker.id, 1); + assert.ok(worker instanceof cluster.Worker, + 'the worker is not a instance of the Worker constructor'); + + //Check event + forEach(checks.worker.events, function(bool, name, index) { + worker.on(name, function() { + //Set event + checks.worker.events[name] = true; + + //Check argument + checks.worker.equal[name] = (worker === this); + + switch (name) { + case 'exit': + assert.equal(arguments[0], worker.process.exitCode); + assert.equal(arguments[1], worker.process.signalCode); + assert.equal(arguments.length, 2); + break; + + case 'listening': + assert.equal(arguments.length, 1); + var expect = { address: '127.0.0.1', + port: common.PORT, + addressType: 4, + fd: undefined }; + assert.deepEqual(arguments[0], expect); + break; + + default: + assert.equal(arguments.length, 0); + break; + } + }); + }); + + //Check all values + process.once('exit', function() { + //Check cluster events + forEach(checks.cluster.events, function(check, name) { + assert.ok(check, 'The cluster event "' + name + '" on the cluster ' + + 'object did not fire'); + }); + + //Check cluster event arguments + forEach(checks.cluster.equal, function(check, name) { + assert.ok(check, 'The cluster event "' + name + '" did not emit ' + + 'with correct argument'); + }); + + //Check worker states + forEach(checks.worker.states, function(check, name) { + assert.ok(check, 'The worker state "' + name + '" was not set to true'); + }); + + //Check worker events + forEach(checks.worker.events, function(check, name) { + assert.ok(check, 'The worker event "' + name + '" on the worker object ' + + 'did not fire'); + }); + + //Check worker event arguments + forEach(checks.worker.equal, function(check, name) { + assert.ok(check, 'The worker event "' + name + '" did not emit with ' + + 'corrent argument'); + }); + }); + +} diff --git a/test/parallel/test-cluster-bind-privileged-port.js b/test/parallel/test-cluster-bind-privileged-port.js new file mode 100644 index 000000000..b76757728 --- /dev/null +++ b/test/parallel/test-cluster-bind-privileged-port.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (process.platform === 'win32') { + console.log('Skipping test, not reliable on Windows.'); + process.exit(0); +} + +if (process.getuid() === 0) { + console.log('Do not run this test as root.'); + process.exit(0); +} + +if (cluster.isMaster) { + cluster.fork().on('exit', common.mustCall(function(exitCode) { + assert.equal(exitCode, 0); + })); +} +else { + var s = net.createServer(assert.fail); + s.listen(42, assert.fail.bind(null, 'listen should have failed')); + s.on('error', common.mustCall(function(err) { + assert.equal(err.code, 'EACCES'); + process.disconnect(); + })); +} diff --git a/test/parallel/test-cluster-bind-twice.js b/test/parallel/test-cluster-bind-twice.js new file mode 100644 index 000000000..311bc60fa --- /dev/null +++ b/test/parallel/test-cluster-bind-twice.js @@ -0,0 +1,129 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This test starts two clustered HTTP servers on the same port. It expects the +// first cluster to succeed and the second cluster to fail with EADDRINUSE. +// +// The test may seem complex but most of it is plumbing that routes messages +// from the child processes back to the supervisor. As a tree it looks something +// like this: +// +// +// / \ +// +// / \ +// +// +// The first worker starts a server on a fixed port and fires a ready message +// that is routed to the second worker. When it tries to bind, it expects to +// see an EADDRINUSE error. +// +// See https://github.com/joyent/node/issues/2721 for more details. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var fork = require('child_process').fork; +var http = require('http'); + +var id = process.argv[2]; + +if (!id) { + var a = fork(__filename, ['one']); + var b = fork(__filename, ['two']); + + a.on('exit', function(c) { + if (c) { + b.send('QUIT'); + throw new Error('A exited with ' + c); + } + }); + + b.on('exit', function(c) { + if (c) { + a.send('QUIT'); + throw new Error('B exited with ' + c); + } + }); + + + a.on('message', function(m) { + if (typeof m === 'object') return; + assert.equal(m, 'READY'); + b.send('START'); + }); + + var ok = false; + + b.on('message', function(m) { + if (typeof m === 'object') return; // ignore system messages + assert.equal(m, 'EADDRINUSE'); + ok = true; + a.send('QUIT'); + b.send('QUIT'); + }); + + process.on('exit', function() { + assert(ok); + }); +} +else if (id === 'one') { + if (cluster.isMaster) return startWorker(); + + var server = http.createServer(assert.fail).listen(common.PORT, function() { + process.send('READY'); + }); + + process.on('message', function(m) { + if (m === 'QUIT') process.exit(); + }); +} +else if (id === 'two') { + if (cluster.isMaster) return startWorker(); + + var ok = false; + process.on('exit', function() { + assert(ok); + }); + + var server = http.createServer(assert.fail); + process.on('message', function(m) { + if (typeof m === 'object') return; // ignore system messages + if (m === 'QUIT') process.exit(); + assert.equal(m, 'START'); + server.listen(common.PORT, assert.fail); + server.on('error', function(e) { + assert.equal(e.code, 'EADDRINUSE'); + process.send(e.code); + ok = true; + }); + }); +} +else { + assert(0); // bad command line argument +} + +function startWorker() { + var worker = cluster.fork(); + worker.on('exit', process.exit); + worker.on('message', process.send.bind(process)); + process.on('message', worker.send.bind(worker)); +} diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js new file mode 100644 index 000000000..c6dc095d0 --- /dev/null +++ b/test/parallel/test-cluster-dgram-1.js @@ -0,0 +1,115 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var NUM_WORKERS = 4; +var PACKETS_PER_WORKER = 10; + +var assert = require('assert'); +var cluster = require('cluster'); +var common = require('../common'); +var dgram = require('dgram'); + + +if (process.platform === 'win32') { + console.warn("dgram clustering is currently not supported on windows."); + process.exit(0); +} + +if (cluster.isMaster) + master(); +else + worker(); + + +function master() { + var listening = 0; + + // Fork 4 workers. + for (var i = 0; i < NUM_WORKERS; i++) + cluster.fork(); + + // Wait until all workers are listening. + cluster.on('listening', function() { + if (++listening < NUM_WORKERS) + return; + + // Start sending messages. + var buf = new Buffer('hello world'); + var socket = dgram.createSocket('udp4'); + var sent = 0; + doSend(); + + function doSend() { + socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1', afterSend); + } + + function afterSend() { + sent++; + if (sent < NUM_WORKERS * PACKETS_PER_WORKER) { + doSend(); + } else { + console.log('master sent %d packets', sent); + socket.close(); + } + } + }); + + // Set up event handlers for every worker. Each worker sends a message when + // it has received the expected number of packets. After that it disconnects. + for (var key in cluster.workers) { + if (cluster.workers.hasOwnProperty(key)) + setupWorker(cluster.workers[key]); + } + + function setupWorker(worker) { + var received = 0; + + worker.on('message', function(msg) { + received = msg.received; + console.log('worker %d received %d packets', worker.id, received); + }); + + worker.on('disconnect', function() { + assert(received === PACKETS_PER_WORKER); + console.log('worker %d disconnected', worker.id); + }); + } +} + + +function worker() { + var received = 0; + + // Create udp socket and start listening. + var socket = dgram.createSocket('udp4'); + + socket.on('message', function(data, info) { + received++; + + // Every 10 messages, notify the master. + if (received == PACKETS_PER_WORKER) { + process.send({received: received}); + process.disconnect(); + } + }); + + socket.bind(common.PORT); +} diff --git a/test/parallel/test-cluster-dgram-2.js b/test/parallel/test-cluster-dgram-2.js new file mode 100644 index 000000000..cb5eaf067 --- /dev/null +++ b/test/parallel/test-cluster-dgram-2.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var NUM_WORKERS = 4; +var PACKETS_PER_WORKER = 10; + +var assert = require('assert'); +var cluster = require('cluster'); +var common = require('../common'); +var dgram = require('dgram'); + + +if (process.platform === 'win32') { + console.warn("dgram clustering is currently not supported on windows."); + process.exit(0); +} + +if (cluster.isMaster) + master(); +else + worker(); + + +function master() { + var i; + var received = 0; + + // Start listening on a socket. + var socket = dgram.createSocket('udp4'); + socket.bind(common.PORT); + + // Disconnect workers when the expected number of messages have been + // received. + socket.on('message', function(data, info) { + received++; + + if (received == PACKETS_PER_WORKER * NUM_WORKERS) { + console.log('master received %d packets', received); + + // Close the socket. + socket.close(); + + // Disconnect all workers. + cluster.disconnect(); + } + }); + + // Fork workers. + for (var i = 0; i < NUM_WORKERS; i++) + cluster.fork(); +} + + +function worker() { + // Create udp socket and send packets to master. + var socket = dgram.createSocket('udp4'); + var buf = new Buffer('hello world'); + + for (var i = 0; i < PACKETS_PER_WORKER; i++) + socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1'); + + console.log('worker %d sent %d packets', cluster.worker.id, PACKETS_PER_WORKER); +} diff --git a/test/parallel/test-cluster-disconnect-idle-worker.js b/test/parallel/test-cluster-disconnect-idle-worker.js new file mode 100644 index 000000000..9c79ad779 --- /dev/null +++ b/test/parallel/test-cluster-disconnect-idle-worker.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isMaster) { + cluster.fork(); + cluster.fork(); + cluster.disconnect(common.mustCall(function() { + assert.deepEqual(Object.keys(cluster.workers), []); + })); +} diff --git a/test/parallel/test-cluster-disconnect-with-no-workers.js b/test/parallel/test-cluster-disconnect-with-no-workers.js new file mode 100644 index 000000000..48e3b0925 --- /dev/null +++ b/test/parallel/test-cluster-disconnect-with-no-workers.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var cluster = require('cluster'); + +var disconnected; + +process.on('exit', function() { + assert(disconnected); +}); + +cluster.disconnect(function() { + disconnected = true; +}); + +// Assert that callback is not sometimes synchronous +assert(!disconnected); diff --git a/test/parallel/test-cluster-disconnect.js b/test/parallel/test-cluster-disconnect.js new file mode 100644 index 000000000..797c17d76 --- /dev/null +++ b/test/parallel/test-cluster-disconnect.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isWorker) { + net.createServer(function(socket) { + socket.end('echo'); + }).listen(common.PORT, '127.0.0.1'); + + net.createServer(function(socket) { + socket.end('echo'); + }).listen(common.PORT + 1, '127.0.0.1'); + +} else if (cluster.isMaster) { + var servers = 2; + + // test a single TCP server + var testConnection = function(port, cb) { + var socket = net.connect(port, '127.0.0.1', function() { + // buffer result + var result = ''; + socket.on('data', function(chunk) { result += chunk; }); + + // check result + socket.on('end', function() { + cb(result === 'echo'); + }); + }); + }; + + // test both servers created in the cluster + var testCluster = function(cb) { + var done = 0; + + for (var i = 0, l = servers; i < l; i++) { + testConnection(common.PORT + i, function(success) { + assert.ok(success); + done += 1; + if (done === servers) { + cb(); + } + }); + } + }; + + // start two workers and execute callback when both is listening + var startCluster = function(cb) { + var workers = 8; + var online = 0; + + for (var i = 0, l = workers; i < l; i++) { + + var worker = cluster.fork(); + worker.on('listening', function() { + online += 1; + if (online === workers * servers) { + cb(); + } + }); + } + }; + + + var results = { + start: 0, + test: 0, + disconnect: 0 + }; + + var test = function(again) { + //1. start cluster + startCluster(function() { + results.start += 1; + + //2. test cluster + testCluster(function() { + results.test += 1; + + //3. disconnect cluster + cluster.disconnect(function() { + results.disconnect += 1; + + // run test again to confirm cleanup + if (again) { + test(); + } + }); + }); + }); + }; + + test(true); + + process.once('exit', function() { + assert.equal(results.start, 2); + assert.equal(results.test, 2); + assert.equal(results.disconnect, 2); + }); +} diff --git a/test/parallel/test-cluster-eaccess.js b/test/parallel/test-cluster-eaccess.js new file mode 100644 index 000000000..d5584242c --- /dev/null +++ b/test/parallel/test-cluster-eaccess.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test that errors propagated from cluster children are properly received in their master +// creates an EADDRINUSE condition by also forking a child process to listen on a socket + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var fork = require('child_process').fork; +var fs = require('fs'); +var net = require('net'); + + +if (cluster.isMaster) { + var worker = cluster.fork(); + var gotError = 0; + worker.on('message', function(err) { + gotError++; + console.log(err); + assert.strictEqual('EADDRINUSE', err.code); + worker.disconnect(); + }); + process.on('exit', function() { + console.log('master exited'); + try { + fs.unlinkSync(common.PIPE); + } catch (e) { + } + assert.equal(gotError, 1); + }); +} else { + var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', { stdio: 'inherit' }); + + // message from the child indicates it's ready and listening + cp.on('message', function() { + var server = net.createServer().listen(common.PIPE, function() { + console.log('parent listening, should not be!'); + }); + + server.on('error', function(err) { + console.log('parent error, ending'); + // message to child process tells it to exit + cp.send('end'); + // propagate error to parent + process.send(err); + }); + }); +} diff --git a/test/parallel/test-cluster-eaddrinuse.js b/test/parallel/test-cluster-eaddrinuse.js new file mode 100644 index 000000000..73b1df0a5 --- /dev/null +++ b/test/parallel/test-cluster-eaddrinuse.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Check that having a worker bind to a port that's already taken doesn't +// leave the master process in a confused state. Releasing the port and +// trying again should Just Work[TM]. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var fork = require('child_process').fork; +var net = require('net'); + +var id = '' + process.argv[2]; + +if (id === 'undefined') { + var server = net.createServer(assert.fail); + server.listen(common.PORT, function() { + var worker = fork(__filename, ['worker']); + worker.on('message', function(msg) { + if (msg !== 'stop-listening') return; + server.close(function() { + worker.send('stopped-listening'); + }); + }); + }); +} +else if (id === 'worker') { + var server = net.createServer(assert.fail); + server.listen(common.PORT, assert.fail); + server.on('error', common.mustCall(function(e) { + assert(e.code, 'EADDRINUSE'); + process.send('stop-listening'); + process.once('message', function(msg) { + if (msg !== 'stopped-listening') return; + server = net.createServer(assert.fail); + server.listen(common.PORT, common.mustCall(function() { + server.close(); + })); + }); + })); +} +else { + assert(0); // Bad argument. +} diff --git a/test/parallel/test-cluster-fork-env.js b/test/parallel/test-cluster-fork-env.js new file mode 100644 index 000000000..a0b50aebd --- /dev/null +++ b/test/parallel/test-cluster-fork-env.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + cluster.worker.send({ + prop: process.env['cluster_test_prop'], + overwrite: process.env['cluster_test_overwrite'] + }); + +} else if (cluster.isMaster) { + + var checks = { + using: false, + overwrite: false + }; + + // To check that the cluster extend on the process.env we will overwrite a + // property + process.env['cluster_test_overwrite'] = 'old'; + + // Fork worker + var worker = cluster.fork({ + 'cluster_test_prop': 'custom', + 'cluster_test_overwrite': 'new' + }); + + // Checks worker env + worker.on('message', function(data) { + checks.using = (data.prop === 'custom'); + checks.overwrite = (data.overwrite === 'new'); + process.exit(0); + }); + + process.once('exit', function() { + assert.ok(checks.using, 'The worker did not receive the correct env.'); + assert.ok(checks.overwrite, 'The custom environment did not overwrite ' + + 'the existing environment.'); + }); + +} diff --git a/test/parallel/test-cluster-http-pipe.js b/test/parallel/test-cluster-http-pipe.js new file mode 100644 index 000000000..7123bf627 --- /dev/null +++ b/test/parallel/test-cluster-http-pipe.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// It is not possible to send pipe handles over the IPC pipe on Windows. +if (process.platform === 'win32') { + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var http = require('http'); + +if (cluster.isMaster) { + var ok = false; + var worker = cluster.fork(); + worker.on('message', function(msg) { + assert.equal(msg, 'DONE'); + ok = true; + }); + worker.on('exit', function() { + process.exit(); + }); + process.on('exit', function() { + assert(ok); + }); + return; +} + +http.createServer(function(req, res) { + assert.equal(req.connection.remoteAddress, undefined); + assert.equal(req.connection.localAddress, undefined); // TODO common.PIPE? + res.writeHead(200); + res.end('OK'); +}).listen(common.PIPE, function() { + var self = this; + http.get({ socketPath: common.PIPE, path: '/' }, function(res) { + res.resume(); + res.on('end', function(err) { + if (err) throw err; + process.send('DONE'); + process.exit(); + }); + }); +}); diff --git a/test/parallel/test-cluster-master-error.js b/test/parallel/test-cluster-master-error.js new file mode 100644 index 000000000..ee2ed9eb4 --- /dev/null +++ b/test/parallel/test-cluster-master-error.js @@ -0,0 +1,140 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +// Cluster setup +if (cluster.isWorker) { + var http = require('http'); + http.Server(function() { + + }).listen(common.PORT, '127.0.0.1'); + +} else if (process.argv[2] === 'cluster') { + + var totalWorkers = 2; + + // Send PID to testcase process + var forkNum = 0; + cluster.on('fork', function forkEvent(worker) { + + // Send PID + process.send({ + cmd: 'worker', + workerPID: worker.process.pid + }); + + // Stop listening when done + if (++forkNum === totalWorkers) { + cluster.removeListener('fork', forkEvent); + } + }); + + // Throw accidently error when all workers are listening + var listeningNum = 0; + cluster.on('listening', function listeningEvent() { + + // When all workers are listening + if (++listeningNum === totalWorkers) { + // Stop listening + cluster.removeListener('listening', listeningEvent); + + // throw accidently error + process.nextTick(function() { + console.error('about to throw'); + throw new Error('accidently error'); + }); + } + + }); + + // Startup a basic cluster + cluster.fork(); + cluster.fork(); + +} else { + // This is the testcase + + var fork = require('child_process').fork; + + var isAlive = function(pid) { + try { + //this will throw an error if the process is dead + process.kill(pid, 0); + + return true; + } catch (e) { + return false; + } + }; + + var existMaster = false; + var existWorker = false; + + // List all workers + var workers = []; + + // Spawn a cluster process + var master = fork(process.argv[1], ['cluster'], {silent: true}); + + // Handle messages from the cluster + master.on('message', function(data) { + + // Add worker pid to list and progress tracker + if (data.cmd === 'worker') { + workers.push(data.workerPID); + } + }); + + // When cluster is dead + master.on('exit', function(code) { + + // Check that the cluster died accidently + existMaster = !!code; + + // Give the workers time to shut down + setTimeout(checkWorkers, 200); + + function checkWorkers() { + // When master is dead all workers should be dead to + var alive = false; + workers.forEach(function(pid) { + if (isAlive(pid)) { + alive = true; + } + }); + + // If a worker was alive this did not act as expected + existWorker = !alive; + } + }); + + process.once('exit', function() { + var m = 'The master did not die after an error was throwed'; + assert.ok(existMaster, m); + m = 'The workers did not die after an error in the master'; + assert.ok(existWorker, m); + }); + +} diff --git a/test/parallel/test-cluster-master-kill.js b/test/parallel/test-cluster-master-kill.js new file mode 100644 index 000000000..362540390 --- /dev/null +++ b/test/parallel/test-cluster-master-kill.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + + // keep the worker alive + var http = require('http'); + http.Server().listen(common.PORT, '127.0.0.1'); + +} else if (process.argv[2] === 'cluster') { + + var worker = cluster.fork(); + + // send PID info to testcase process + process.send({ + pid: worker.process.pid + }); + + // terminate the cluster process + worker.once('listening', function() { + setTimeout(function() { + process.exit(0); + }, 1000); + }); + +} else { + + // This is the testcase + var fork = require('child_process').fork; + + // is process alive helper + var isAlive = function(pid) { + try { + //this will throw an error if the process is dead + process.kill(pid, 0); + + return true; + } catch (e) { + return false; + } + }; + + // Spawn a cluster process + var master = fork(process.argv[1], ['cluster']); + + // get pid info + var pid = null; + master.once('message', function(data) { + pid = data.pid; + }); + + // When master is dead + var alive = true; + master.on('exit', function(code) { + + // make sure that the master died by purpose + assert.equal(code, 0); + + // check worker process status + setTimeout(function() { + alive = isAlive(pid); + }, 200); + }); + + process.once('exit', function() { + // cleanup: kill the worker if alive + if (alive) { + process.kill(pid); + } + + assert.equal(typeof pid, 'number', 'did not get worker pid info'); + assert.equal(alive, false, 'worker was alive after master died'); + }); + +} diff --git a/test/parallel/test-cluster-message.js b/test/parallel/test-cluster-message.js new file mode 100644 index 000000000..7407515ad --- /dev/null +++ b/test/parallel/test-cluster-message.js @@ -0,0 +1,141 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +function forEach(obj, fn) { + Object.keys(obj).forEach(function(name, index) { + fn(obj[name], name, index); + }); +} + +if (cluster.isWorker) { + // Create a tcp server. This will be used as cluster-shared-server and as an + // alternative IPC channel. + var server = net.Server(); + var socket, message; + + function maybeReply() { + if (!socket || !message) return; + + // Tell master using TCP socket that a message is received. + socket.write(JSON.stringify({ + code: 'received message', + echo: message + })); + } + + server.on('connection', function(socket_) { + socket = socket_; + maybeReply(); + + // Send a message back over the IPC channel. + process.send('message from worker'); + }); + + process.on('message', function(message_) { + message = message_; + maybeReply(); + }); + + server.listen(common.PORT, '127.0.0.1'); +} + +else if (cluster.isMaster) { + + var checks = { + master: { + 'receive': false, + 'correct': false + }, + worker: { + 'receive': false, + 'correct': false + } + }; + + + var client; + var check = function(type, result) { + checks[type].receive = true; + checks[type].correct = result; + console.error('check', checks); + + var missing = false; + forEach(checks, function(type) { + if (type.receive === false) missing = true; + }); + + if (missing === false) { + console.error('end client'); + client.end(); + } + }; + + // Spawn worker + var worker = cluster.fork(); + + // When a IPC message is received form the worker + worker.on('message', function(message) { + check('master', message === 'message from worker'); + }); + + // When a TCP connection is made with the worker connect to it + worker.on('listening', function() { + + client = net.connect(common.PORT, function() { + // Send message to worker. + worker.send('message from master'); + }); + + client.on('data', function(data) { + // All data is JSON + data = JSON.parse(data.toString()); + + if (data.code === 'received message') { + check('worker', data.echo === 'message from master'); + } else { + throw new Error('wrong TCP message recived: ' + data); + } + }); + + // When the connection ends kill worker and shutdown process + client.on('end', function() { + worker.kill(); + }); + + worker.on('exit', function() { + process.exit(0); + }); + }); + + process.once('exit', function() { + forEach(checks, function(check, type) { + assert.ok(check.receive, 'The ' + type + ' did not receive any message'); + assert.ok(check.correct, + 'The ' + type + ' did not get the correct message'); + }); + }); +} diff --git a/test/parallel/test-cluster-net-listen.js b/test/parallel/test-cluster-net-listen.js new file mode 100644 index 000000000..927169c72 --- /dev/null +++ b/test/parallel/test-cluster-net-listen.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isMaster) { + // ensure that the worker exits peacefully + var worker = cluster.fork(); + worker.on('exit', function(statusCode) { + assert.equal(statusCode, 0); + worker = null; + }); + process.on('exit', function() { + assert.equal(worker, null); + }); +} +else { + // listen() without port should not trigger a libuv assert + net.createServer(assert.fail).listen(process.exit); +} diff --git a/test/parallel/test-cluster-net-send.js b/test/parallel/test-cluster-net-send.js new file mode 100644 index 000000000..1313a624a --- /dev/null +++ b/test/parallel/test-cluster-net-send.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fork = require('child_process').fork; +var net = require('net'); + +if (process.argv[2] !== 'child') { + console.error('[%d] master', process.pid); + + var worker = fork(__filename, ['child']); + var called = false; + + worker.once('message', function(msg, handle) { + assert.equal(msg, 'handle'); + assert.ok(handle); + worker.send('got'); + + handle.on('data', function(data) { + called = true; + assert.equal(data.toString(), 'hello'); + }); + + handle.on('end', function() { + worker.kill(); + }); + }); + + process.once('exit', function() { + assert.ok(called); + }); +} else { + console.error('[%d] worker', process.pid); + + var server = net.createServer(function(c) { + process.once('message', function(msg) { + assert.equal(msg, 'got'); + c.end('hello'); + }); + }); + server.listen(common.PORT, function() { + var socket = net.connect(common.PORT, '127.0.0.1', function() { + process.send('handle', socket); + }); + }); + + process.on('disconnect', function() { + process.exit(); + server.close(); + }); +} diff --git a/test/parallel/test-cluster-rr-domain-listen.js b/test/parallel/test-cluster-rr-domain-listen.js new file mode 100755 index 000000000..574036df2 --- /dev/null +++ b/test/parallel/test-cluster-rr-domain-listen.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var cluster = require('cluster'); +var domain = require('domain'); + +// RR is the default for v0.11.9+ so the following line is redundant: +// cluster.schedulingPolicy = cluster.SCHED_RR; + +if (cluster.isWorker) { + var d = domain.create(); + d.run(function () { }); + + var http = require('http'); + http.Server(function() { }).listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + var worker; + + //Kill worker when listening + cluster.on('listening', function() { + worker.kill(); + }); + + //Kill process when worker is killed + cluster.on('exit', function() { + process.exit(0); + }); + + //Create worker + worker = cluster.fork(); +} diff --git a/test/parallel/test-cluster-send-deadlock.js b/test/parallel/test-cluster-send-deadlock.js new file mode 100644 index 000000000..1b4a90dee --- /dev/null +++ b/test/parallel/test-cluster-send-deadlock.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Testing mutual send of handles: from master to worker, and from worker to +// master. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isMaster) { + var worker = cluster.fork(); + worker.on('exit', function(code, signal) { + assert.equal(code, 0, 'Worker exited with an error code'); + assert(!signal, 'Worker exited by a signal'); + server.close(); + }); + + var server = net.createServer(function(socket) { + worker.send('handle', socket); + }); + + server.listen(common.PORT, function() { + worker.send('listen'); + }); +} else { + process.on('message', function(msg, handle) { + if (msg === 'listen') { + var client1 = net.connect({ host: 'localhost', port: common.PORT }); + var client2 = net.connect({ host: 'localhost', port: common.PORT }); + var waiting = 2; + client1.on('close', onclose); + client2.on('close', onclose); + function onclose() { + if (--waiting === 0) + cluster.worker.disconnect(); + } + setTimeout(function() { + client1.end(); + client2.end(); + }, 50); + } else { + process.send('reply', handle); + } + }); +} diff --git a/test/parallel/test-cluster-send-handle-twice.js b/test/parallel/test-cluster-send-handle-twice.js new file mode 100644 index 000000000..3215eae79 --- /dev/null +++ b/test/parallel/test-cluster-send-handle-twice.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Testing to send an handle twice to the parent process. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +var workers = { + toStart: 1 +}; + +if (cluster.isMaster) { + for (var i = 0; i < workers.toStart; ++i) { + var worker = cluster.fork(); + worker.on('exit', function(code, signal) { + assert.equal(code, 0, 'Worker exited with an error code'); + assert(!signal, 'Worker exited by a signal'); + }); + } +} else { + var server = net.createServer(function(socket) { + process.send('send-handle-1', socket); + process.send('send-handle-2', socket); + }); + + server.listen(common.PORT, function() { + var client = net.connect({ host: 'localhost', port: common.PORT }); + client.on('close', function() { cluster.worker.disconnect(); }); + setTimeout(function() { client.end(); }, 50); + }).on('error', function(e) { + console.error(e); + assert(false, 'server.listen failed'); + cluster.worker.disconnect(); + }); +} diff --git a/test/parallel/test-cluster-setup-master-argv.js b/test/parallel/test-cluster-setup-master-argv.js new file mode 100644 index 000000000..d216943c8 --- /dev/null +++ b/test/parallel/test-cluster-setup-master-argv.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +setTimeout(assert.fail.bind(assert, 'setup not emitted'), 1000).unref(); + +cluster.on('setup', function() { + var clusterArgs = cluster.settings.args; + var realArgs = process.argv; + assert.equal(clusterArgs[clusterArgs.length - 1], + realArgs[realArgs.length - 1]); +}); + +assert(process.argv[process.argv.length - 1] !== 'OMG,OMG'); +process.argv.push('OMG,OMG'); +process.argv.push('OMG,OMG'); +cluster.setupMaster(); diff --git a/test/parallel/test-cluster-setup-master-cumulative.js b/test/parallel/test-cluster-setup-master-cumulative.js new file mode 100644 index 000000000..2f69cd368 --- /dev/null +++ b/test/parallel/test-cluster-setup-master-cumulative.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +assert(cluster.isMaster); + +assert.deepEqual(cluster.settings, {}, + 'cluster.settings should not be initialized until needed'); + +cluster.setupMaster(); +assert.deepEqual(cluster.settings, { + args: process.argv.slice(2), + exec: process.argv[1], + execArgv: process.execArgv, + silent: false, +}); +console.log('ok sets defaults'); + +cluster.setupMaster({ exec: 'overridden' }); +assert.strictEqual(cluster.settings.exec, 'overridden'); +console.log('ok overrids defaults'); + +cluster.setupMaster({ args: ['foo', 'bar'] }); +assert.strictEqual(cluster.settings.exec, 'overridden'); +assert.deepEqual(cluster.settings.args, ['foo', 'bar']); + +cluster.setupMaster({ execArgv: ['baz', 'bang'] }); +assert.strictEqual(cluster.settings.exec, 'overridden'); +assert.deepEqual(cluster.settings.args, ['foo', 'bar']); +assert.deepEqual(cluster.settings.execArgv, ['baz', 'bang']); +console.log('ok preserves unchanged settings on repeated calls'); + +cluster.setupMaster(); +assert.deepEqual(cluster.settings, { + args: ['foo', 'bar'], + exec: 'overridden', + execArgv: ['baz', 'bang'], + silent: false, +}); +console.log('ok preserves current settings'); diff --git a/test/parallel/test-cluster-setup-master-emit.js b/test/parallel/test-cluster-setup-master-emit.js new file mode 100644 index 000000000..ee3af2ad4 --- /dev/null +++ b/test/parallel/test-cluster-setup-master-emit.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +assert(cluster.isMaster); + +var assertsRun = 0; + +function emitAndCatch(next) { + cluster.once('setup', function(settings) { + assert.strictEqual(settings.exec, 'new-exec'); + console.log('ok "setup" emitted with options set'); + assertsRun += 1; + setImmediate(next); + }); + cluster.setupMaster({ exec: 'new-exec' }); +} + +function emitAndCatch2(next) { + cluster.once('setup', function(settings) { + assert('exec' in settings); + console.log('ok "setup" emitted without options set'); + assertsRun += 1; + setImmediate(next); + }); + cluster.setupMaster(); +} + +process.on('exit', function() { + assert.strictEqual(assertsRun, 2); + console.log('ok correct number of assertions'); +}); + +emitAndCatch(function() { + emitAndCatch2(function() { + console.log('ok emitted and caught'); + }); +}); diff --git a/test/parallel/test-cluster-setup-master-multiple.js b/test/parallel/test-cluster-setup-master-multiple.js new file mode 100644 index 000000000..21756b9c0 --- /dev/null +++ b/test/parallel/test-cluster-setup-master-multiple.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +assert(cluster.isMaster); + +// The cluster.settings object is cloned even though the current implementation +// makes that unecessary. This is to make the test less fragile if the +// implementation ever changes such that cluster.settings is mutated instead of +// replaced. +function cheapClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} + +var configs = []; + +// Capture changes +cluster.on('setup', function() { + console.log('"setup" emitted', cluster.settings); + configs.push(cheapClone(cluster.settings)); +}); + +var execs = [ + 'node-next', + 'node-next-2', + 'node-next-3', +]; + +process.on('exit', function assertTests() { + // Tests that "setup" is emitted for every call to setupMaster + assert.strictEqual(configs.length, execs.length); + + assert.strictEqual(configs[0].exec, execs[0]); + assert.strictEqual(configs[1].exec, execs[1]); + assert.strictEqual(configs[2].exec, execs[2]); +}); + +// Make changes to cluster settings +execs.forEach(function(v, i) { + setTimeout(function() { + cluster.setupMaster({ exec: v }); + }, i * 100); +}); + +// cluster emits 'setup' asynchronously, so we must stay alive long +// enough for that to happen +setTimeout(function() { + console.log('cluster setup complete'); +}, (execs.length + 1) * 100); diff --git a/test/parallel/test-cluster-setup-master.js b/test/parallel/test-cluster-setup-master.js new file mode 100644 index 000000000..d9f387928 --- /dev/null +++ b/test/parallel/test-cluster-setup-master.js @@ -0,0 +1,90 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + + // Just keep the worker alive + process.send(process.argv[2]); + +} else if (cluster.isMaster) { + + var checks = { + args: false, + setupEvent: false, + settingsObject: false + }; + + var totalWorkers = 2; + + // Setup master + cluster.setupMaster({ + args: ['custom argument'], + silent: true + }); + + cluster.once('setup', function() { + checks.setupEvent = true; + + var settings = cluster.settings; + if (settings && + settings.args && settings.args[0] === 'custom argument' && + settings.silent === true && + settings.exec === process.argv[1]) { + checks.settingsObject = true; + } + }); + + var correctIn = 0; + + cluster.on('online', function lisenter(worker) { + + worker.once('message', function(data) { + correctIn += (data === 'custom argument' ? 1 : 0); + if (correctIn === totalWorkers) { + checks.args = true; + } + worker.kill(); + }); + + // All workers are online + if (cluster.onlineWorkers === totalWorkers) { + checks.workers = true; + } + }); + + // Start all workers + cluster.fork(); + cluster.fork(); + + // Check all values + process.once('exit', function() { + assert.ok(checks.args, 'The arguments was noy send to the worker'); + assert.ok(checks.setupEvent, 'The setup event was never emitted'); + var m = 'The settingsObject do not have correct properties'; + assert.ok(checks.settingsObject, m); + }); + +} diff --git a/test/parallel/test-cluster-shared-handle-bind-error.js b/test/parallel/test-cluster-shared-handle-bind-error.js new file mode 100644 index 000000000..ceccd9146 --- /dev/null +++ b/test/parallel/test-cluster-shared-handle-bind-error.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isMaster) { + // Master opens and binds the socket and shares it with the worker. + cluster.schedulingPolicy = cluster.SCHED_NONE; + // Hog the TCP port so that when the worker tries to bind, it'll fail. + net.createServer(assert.fail).listen(common.PORT, function() { + var server = this; + var worker = cluster.fork(); + worker.on('exit', common.mustCall(function(exitCode) { + assert.equal(exitCode, 0); + server.close(); + })); + }); +} +else { + var s = net.createServer(assert.fail); + s.listen(common.PORT, assert.fail.bind(null, 'listen should have failed')); + s.on('error', common.mustCall(function(err) { + assert.equal(err.code, 'EADDRINUSE'); + process.disconnect(); + })); +} diff --git a/test/parallel/test-cluster-shared-handle-bind-privileged-port.js b/test/parallel/test-cluster-shared-handle-bind-privileged-port.js new file mode 100644 index 000000000..67b3a8840 --- /dev/null +++ b/test/parallel/test-cluster-shared-handle-bind-privileged-port.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (process.platform === 'win32') { + console.log('Skipping test, not reliable on Windows.'); + process.exit(0); +} + +if (process.getuid() === 0) { + console.log('Do not run this test as root.'); + process.exit(0); +} + +if (cluster.isMaster) { + // Master opens and binds the socket and shares it with the worker. + cluster.schedulingPolicy = cluster.SCHED_NONE; + cluster.fork().on('exit', common.mustCall(function(exitCode) { + assert.equal(exitCode, 0); + })); +} +else { + var s = net.createServer(assert.fail); + s.listen(42, assert.fail.bind(null, 'listen should have failed')); + s.on('error', common.mustCall(function(err) { + assert.equal(err.code, 'EACCES'); + process.disconnect(); + })); +} diff --git a/test/parallel/test-cluster-uncaught-exception.js b/test/parallel/test-cluster-uncaught-exception.js new file mode 100644 index 000000000..48a825127 --- /dev/null +++ b/test/parallel/test-cluster-uncaught-exception.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Installing a custom uncaughtException handler should override the default +// one that the cluster module installs. +// https://github.com/joyent/node/issues/2556 + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var fork = require('child_process').fork; + +var MAGIC_EXIT_CODE = 42; + +var isTestRunner = process.argv[2] != 'child'; + +if (isTestRunner) { + var exitCode = -1; + + process.on('exit', function() { + assert.equal(exitCode, MAGIC_EXIT_CODE); + }); + + var master = fork(__filename, ['child']); + master.on('exit', function(code) { + exitCode = code; + }); +} +else if (cluster.isMaster) { + process.on('uncaughtException', function() { + process.nextTick(function() { + process.exit(MAGIC_EXIT_CODE); + }); + }); + + cluster.fork(); + throw new Error('kill master'); +} +else { // worker + process.exit(); +} diff --git a/test/parallel/test-cluster-worker-constructor.js b/test/parallel/test-cluster-worker-constructor.js new file mode 100644 index 000000000..ce7945cdb --- /dev/null +++ b/test/parallel/test-cluster-worker-constructor.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// test-cluster-worker-constructor.js +// validates correct behavior of the cluster.Worker constructor + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var worker; + +worker = new cluster.Worker(); +assert.equal(worker.suicide, undefined); +assert.equal(worker.state, 'none'); +assert.equal(worker.id, 0); +assert.equal(worker.process, undefined); + +worker = new cluster.Worker({ + id: 3, + state: 'online', + process: process +}); +assert.equal(worker.suicide, undefined); +assert.equal(worker.state, 'online'); +assert.equal(worker.id, 3); +assert.equal(worker.process, process); + +worker = cluster.Worker.call({}, {id: 5}); +assert(worker instanceof cluster.Worker); +assert.equal(worker.id, 5); diff --git a/test/parallel/test-cluster-worker-death.js b/test/parallel/test-cluster-worker-death.js new file mode 100644 index 000000000..ccd48552a --- /dev/null +++ b/test/parallel/test-cluster-worker-death.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (!cluster.isMaster) { + process.exit(42); +} +else { + var seenExit = 0; + var seenDeath = 0; + var worker = cluster.fork(); + worker.on('exit', function(exitCode, signalCode) { + assert.equal(exitCode, 42); + assert.equal(signalCode, null); + seenExit++; + }); + cluster.on('exit', function(worker_) { + assert.equal(worker_, worker); + seenDeath++; + }); + process.on('exit', function() { + assert.equal(seenExit, 1); + assert.equal(seenDeath, 1); + }); +} diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js new file mode 100644 index 000000000..318b55caf --- /dev/null +++ b/test/parallel/test-cluster-worker-destroy.js @@ -0,0 +1,79 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * The goal of this test is to cover the Workers' implementation of + * Worker.prototype.destroy. Worker.prototype.destroy is called within + * the worker's context: once when the worker is still connected to the + * master, and another time when it's not connected to it, so that we cover + * both code paths. + */ + +require('../common'); +var cluster = require('cluster'); +var assert = require('assert'); + +var worker1, worker2, workerExited, workerDisconnected; + +if (cluster.isMaster) { + worker1 = cluster.fork(); + worker2 = cluster.fork(); + + workerExited = 0; + workerDisconnected = 0; + + [worker1, worker2].forEach(function(worker) { + worker.on('disconnect', ondisconnect); + worker.on('exit', onexit); + }); + + process.on('exit', onProcessExit); + +} else { + if (cluster.worker.id === 1) { + // Call destroy when worker is disconnected + cluster.worker.process.on('disconnect', function() { + cluster.worker.destroy(); + }); + + cluster.worker.disconnect(); + } else { + // Call destroy when worker is not disconnected yet + cluster.worker.destroy(); + } +} + +function onProcessExit() { + assert.equal(workerExited, + 2, + 'When master exits, all workers should have exited too'); + assert.equal(workerDisconnected, + 2, + 'When master exits, all workers should have disconnected'); +} + +function ondisconnect() { + ++workerDisconnected; +} + +function onexit() { + ++workerExited; +} diff --git a/test/parallel/test-cluster-worker-disconnect.js b/test/parallel/test-cluster-worker-disconnect.js new file mode 100644 index 000000000..632a25f2d --- /dev/null +++ b/test/parallel/test-cluster-worker-disconnect.js @@ -0,0 +1,110 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + var http = require('http'); + http.Server(function() { + + }).listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + + var checks = { + cluster: { + emitDisconnect: false, + emitExit: false, + callback: false + }, + worker: { + emitDisconnect: false, + emitExit: false, + state: false, + suicideMode: false, + died: false + } + }; + + // helper function to check if a process is alive + var alive = function(pid) { + try { + process.kill(pid, 0); + return true; + } catch (e) { + return false; + } + }; + + // start worker + var worker = cluster.fork(); + + // Disconnect worker when it is ready + worker.once('listening', function() { + worker.disconnect(); + }); + + // Check cluster events + cluster.once('disconnect', function() { + checks.cluster.emitDisconnect = true; + }); + cluster.once('exit', function() { + checks.cluster.emitExit = true; + }); + + // Check worker events and properties + worker.once('disconnect', function() { + checks.worker.emitDisconnect = true; + checks.worker.suicideMode = worker.suicide; + checks.worker.state = worker.state; + }); + + // Check that the worker died + worker.once('exit', function() { + checks.worker.emitExit = true; + checks.worker.died = !alive(worker.process.pid); + process.nextTick(function() { + process.exit(0); + }); + }); + + process.once('exit', function() { + + var w = checks.worker; + var c = checks.cluster; + + // events + assert.ok(w.emitDisconnect, 'Disconnect event did not emit'); + assert.ok(c.emitDisconnect, 'Disconnect event did not emit'); + assert.ok(w.emitExit, 'Exit event did not emit'); + assert.ok(c.emitExit, 'Exit event did not emit'); + + // flags + assert.equal(w.state, 'disconnected', 'The state property was not set'); + assert.equal(w.suicideMode, true, 'Suicide mode was not set'); + + // is process alive + assert.ok(w.died, 'The worker did not die'); + }); +} diff --git a/test/parallel/test-cluster-worker-events.js b/test/parallel/test-cluster-worker-events.js new file mode 100644 index 000000000..1276650d1 --- /dev/null +++ b/test/parallel/test-cluster-worker-events.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var assert = require('assert'); +var cluster = require('cluster'); + +var OK = 2; + +if (cluster.isMaster) { + + var worker = cluster.fork(); + + worker.on('exit', function(code) { + assert.equal(code, OK); + process.exit(0); + }); + + worker.send('SOME MESSAGE'); + + return; +} + +// Messages sent to a worker will be emitted on both the process object and the +// process.worker object. + +assert(cluster.isWorker); + +var sawProcess; +var sawWorker; + +process.on('message', function(m) { + assert(!sawProcess); + sawProcess = true; + check(m); +}); + +cluster.worker.on('message', function(m) { + assert(!sawWorker); + sawWorker = true; + check(m); +}); + +var messages = []; + +function check(m) { + messages.push(m); + + if (messages.length < 2) return; + + assert.deepEqual(messages[0], messages[1]); + + cluster.worker.once('error', function(e) { + assert.equal(e, 'HI'); + process.exit(OK); + }); + + process.emit('error', 'HI'); +} diff --git a/test/parallel/test-cluster-worker-exit.js b/test/parallel/test-cluster-worker-exit.js new file mode 100644 index 000000000..7b9d5d86c --- /dev/null +++ b/test/parallel/test-cluster-worker-exit.js @@ -0,0 +1,152 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// test-cluster-worker-exit.js +// verifies that, when a child process exits (by calling `process.exit(code)`) +// - the parent receives the proper events in the proper order, no duplicates +// - the exitCode and signalCode are correct in the 'exit' event +// - the worker.suicide flag, and worker.state are correct +// - the worker process actually goes away + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +var EXIT_CODE = 42; + +if (cluster.isWorker) { + var http = require('http'); + var server = http.Server(function() { }); + + server.once('listening', function() { + process.exit(EXIT_CODE); + }); + server.listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + + var expected_results = { + cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], + cluster_emitExit: [1, "the cluster did not emit 'exit'"], + cluster_exitCode: [EXIT_CODE, 'the cluster exited w/ incorrect exitCode'], + cluster_signalCode: [null, 'the cluster exited w/ incorrect signalCode'], + worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], + worker_emitExit: [1, "the worker did not emit 'exit'"], + worker_state: ['disconnected', 'the worker state is incorrect'], + worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], + worker_died: [true, 'the worker is still running'], + worker_exitCode: [EXIT_CODE, 'the worker exited w/ incorrect exitCode'], + worker_signalCode: [null, 'the worker exited w/ incorrect signalCode'] + }; + var results = { + cluster_emitDisconnect: 0, + cluster_emitExit: 0, + worker_emitDisconnect: 0, + worker_emitExit: 0 + }; + + + // start worker + var worker = cluster.fork(); + + worker.once('listening', function() { + // the worker is up and running... + }); + + + // Check cluster events + cluster.on('disconnect', function() { + results.cluster_emitDisconnect += 1; + }); + cluster.on('exit', function(worker) { + results.cluster_exitCode = worker.process.exitCode; + results.cluster_signalCode = worker.process.signalCode; + results.cluster_emitExit += 1; + assert.ok(results.cluster_emitDisconnect, + "cluster: 'exit' event before 'disconnect' event"); + }); + + // Check worker events and properties + worker.on('disconnect', function() { + results.worker_emitDisconnect += 1; + results.worker_suicideMode = worker.suicide; + results.worker_state = worker.state; + }); + + // Check that the worker died + worker.once('exit', function(exitCode, signalCode) { + results.worker_exitCode = exitCode; + results.worker_signalCode = signalCode; + results.worker_emitExit += 1; + results.worker_died = !alive(worker.process.pid); + assert.ok(results.worker_emitDisconnect, + "worker: 'exit' event before 'disconnect' event"); + + process.nextTick(function() { finish_test(); }); + }); + + var finish_test = function() { + try { + checkResults(expected_results, results); + } catch (exc) { + console.error('FAIL: ' + exc.message); + if (exc.name != 'AssertionError') { + console.trace(exc); + } + + process.exit(1); + return; + } + process.exit(0); + }; +} + +// some helper functions ... + + function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; + + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); + } else { + assert.equal(actual, expected, msg); + } + } + } + } + + function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; + } + } diff --git a/test/parallel/test-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js new file mode 100644 index 000000000..66d5f1835 --- /dev/null +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var cluster = require('cluster') +var net = require('net'); + +var SENTINEL = 42; + +// workers forcibly exit when control channel is disconnected, if +// their .suicide flag isn't set +// +// test this by: +// +// 1 setup worker to wait a short time after disconnect, and exit +// with a sentinel value +// 2 disconnect worker with cluster's disconnect, confirm sentinel +// 3 disconnect worker with child_process's disconnect, confirm +// no sentinel value +if (cluster.isWorker) { + process.on('disconnect', function(msg) { + setTimeout(function() { + process.exit(SENTINEL); + }, 10); + }); + return; +} + +var unforcedOk; +var forcedOk; + +process.on('exit', function() { + assert(forcedOk); + assert(unforcedOk); +}); + +checkUnforced(); +checkForced(); + +function checkUnforced() { + cluster.fork() + .on('online', function() { + this.disconnect(); + }) + .on('exit', function(status) { + assert.equal(status, SENTINEL); + unforcedOk = true; + }); +} + +function checkForced() { + cluster.fork() + .on('online', function() { + this.process.disconnect(); + }) + .on('exit', function(status) { + assert.equal(status, 0); + forcedOk = true; + }); +} diff --git a/test/parallel/test-cluster-worker-init.js b/test/parallel/test-cluster-worker-init.js new file mode 100644 index 000000000..f750262e8 --- /dev/null +++ b/test/parallel/test-cluster-worker-init.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// test-cluster-worker-init.js +// verifies that, when a child process is forked, the cluster.worker +// object can receive messages as expected + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var msg = 'foo'; + +if (cluster.isMaster) { + var worker = cluster.fork(); + var timer = setTimeout(function() { + assert(false, 'message not received'); + }, 5000); + + timer.unref(); + + worker.on('message', function(message) { + assert(message, 'did not receive expected message'); + worker.disconnect(); + }); + + worker.on('online', function() { + worker.send(msg); + }); +} else { + // GH #7998 + cluster.worker.on('message', function(message) { + process.send(message === msg); + }); +} diff --git a/test/parallel/test-cluster-worker-isconnected.js b/test/parallel/test-cluster-worker-isconnected.js new file mode 100644 index 000000000..ed839d496 --- /dev/null +++ b/test/parallel/test-cluster-worker-isconnected.js @@ -0,0 +1,37 @@ +var cluster = require('cluster'); +var assert = require('assert'); +var util = require('util'); + +if (cluster.isMaster) { + var worker = cluster.fork(); + + assert.ok(worker.isConnected(), + "isConnected() should return true as soon as the worker has " + + "been created."); + + worker.on('disconnect', function() { + assert.ok(!worker.isConnected(), + "After a disconnect event has been emitted, " + + "isConncted should return false"); + }); + + worker.on('message', function(msg) { + if (msg === 'readyToDisconnect') { + worker.disconnect(); + } + }) + +} else { + assert.ok(cluster.worker.isConnected(), + "isConnected() should return true from within a worker at all " + + "times."); + + cluster.worker.process.on('disconnect', function() { + assert.ok(!cluster.worker.isConnected(), + "isConnected() should return false from within a worker " + + "after its underlying process has been disconnected from " + + "the master"); + }) + + process.send('readyToDisconnect'); +} diff --git a/test/parallel/test-cluster-worker-isdead.js b/test/parallel/test-cluster-worker-isdead.js new file mode 100644 index 000000000..11766c597 --- /dev/null +++ b/test/parallel/test-cluster-worker-isdead.js @@ -0,0 +1,27 @@ +var cluster = require('cluster'); +var assert = require('assert'); +var net = require('net'); + +if (cluster.isMaster) { + var worker = cluster.fork(); + assert.ok(!worker.isDead(), + "isDead() should return false right after the worker has been " + + "created."); + + worker.on('exit', function() { + assert.ok(!worker.isConnected(), + "After an event has been emitted, " + + "isDead should return true"); + }) + + worker.on('message', function(msg) { + if (msg === 'readyToDie') { + worker.kill(); + } + }); + +} else if (cluster.isWorker) { + assert.ok(!cluster.worker.isDead(), + "isDead() should return false when called from within a worker"); + process.send('readyToDie'); +} diff --git a/test/parallel/test-cluster-worker-kill.js b/test/parallel/test-cluster-worker-kill.js new file mode 100644 index 000000000..8c6068e8d --- /dev/null +++ b/test/parallel/test-cluster-worker-kill.js @@ -0,0 +1,149 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// test-cluster-worker-kill.js +// verifies that, when a child process is killed (we use SIGKILL) +// - the parent receives the proper events in the proper order, no duplicates +// - the exitCode and signalCode are correct in the 'exit' event +// - the worker.suicide flag, and worker.state are correct +// - the worker process actually goes away + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); + +if (cluster.isWorker) { + var http = require('http'); + var server = http.Server(function() { }); + + server.once('listening', function() { }); + server.listen(common.PORT, '127.0.0.1'); + +} else if (cluster.isMaster) { + + var KILL_SIGNAL = 'SIGKILL', + expected_results = { + cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], + cluster_emitExit: [1, "the cluster did not emit 'exit'"], + cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], + cluster_signalCode: [KILL_SIGNAL, 'the cluster exited w/ incorrect signalCode'], + worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], + worker_emitExit: [1, "the worker did not emit 'exit'"], + worker_state: ['disconnected', 'the worker state is incorrect'], + worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], + worker_died: [true, 'the worker is still running'], + worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], + worker_signalCode: [KILL_SIGNAL, 'the worker exited w/ incorrect signalCode'] + }, + results = { + cluster_emitDisconnect: 0, + cluster_emitExit: 0, + worker_emitDisconnect: 0, + worker_emitExit: 0 + }; + + + // start worker + var worker = cluster.fork(); + + // when the worker is up and running, kill it + worker.once('listening', function() { + worker.process.kill(KILL_SIGNAL); + }); + + + // Check cluster events + cluster.on('disconnect', function() { + results.cluster_emitDisconnect += 1; + }); + cluster.on('exit', function(worker) { + results.cluster_exitCode = worker.process.exitCode; + results.cluster_signalCode = worker.process.signalCode; + results.cluster_emitExit += 1; + assert.ok(results.cluster_emitDisconnect, + "cluster: 'exit' event before 'disconnect' event"); + }); + + // Check worker events and properties + worker.on('disconnect', function() { + results.worker_emitDisconnect += 1; + results.worker_suicideMode = worker.suicide; + results.worker_state = worker.state; + }); + + // Check that the worker died + worker.once('exit', function(exitCode, signalCode) { + results.worker_exitCode = exitCode; + results.worker_signalCode = signalCode; + results.worker_emitExit += 1; + results.worker_died = !alive(worker.process.pid); + assert.ok(results.worker_emitDisconnect, + "worker: 'exit' event before 'disconnect' event"); + + process.nextTick(function() { finish_test(); }); + }); + + var finish_test = function() { + try { + checkResults(expected_results, results); + } catch (exc) { + console.error('FAIL: ' + exc.message); + if (exc.name != 'AssertionError') { + console.trace(exc); + } + + process.exit(1); + return; + } + process.exit(0); + }; +} + +// some helper functions ... + + function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; + + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); + } else { + assert.equal(actual, expected, msg); + } + } + } + } + + function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; + } + } diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js new file mode 100644 index 000000000..8634d5424 --- /dev/null +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var cluster = require('cluster') +var net = require('net'); +var common = require('../common'); + +var destroyed; +var success; +var worker; +var server; + +// workers do not exit on disconnect, they exit under normal node rules: when +// they have nothing keeping their loop alive, like an active connection +// +// test this by: +// +// 1 creating a server, so worker can make a connection to something +// 2 disconnecting worker +// 3 wait to confirm it did not exit +// 4 destroy connection +// 5 confirm it does exit +if (cluster.isMaster) { + server = net.createServer(function(conn) { + server.close(); + worker.disconnect() + worker.once('disconnect', function() { + setTimeout(function() { + conn.destroy(); + destroyed = true; + }, 1000); + }).once('exit', function() { + // worker should not exit while it has a connection + assert(destroyed, 'worker exited before connection destroyed'); + success = true; + }); + + }).listen(common.PORT, function() { + var port = this.address().port; + + worker = cluster.fork() + .on('online', function() { + this.send({port: port}); + }); + }); + process.on('exit', function() { + assert(success); + }); +} else { + process.on('message', function(msg) { + // we shouldn't exit, not while a network connection exists + net.connect(msg.port); + }); +} diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js new file mode 100644 index 000000000..420bd52a0 --- /dev/null +++ b/test/parallel/test-common.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.globalCheck = false; +global.gc = 42; // Not a valid global unless --expose_gc is set. +assert.deepEqual(common.leakedGlobals(), ['gc']); diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js new file mode 100644 index 000000000..e0166ebd3 --- /dev/null +++ b/test/parallel/test-console-instance.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var Stream = require('stream'); +var Console = require('console').Console; +var called = false; + +// ensure the Console instance doesn't write to the +// process' "stdout" or "stderr" streams +process.stdout.write = process.stderr.write = function() { + throw new Error('write() should not be called!'); +}; + +// make sure that the "Console" function exists +assert.equal('function', typeof Console); + +// make sure that the Console constructor throws +// when not given a writable stream instance +assert.throws(function () { + new Console(); +}, /Console expects a writable stream/); + +var out = new Stream(); +var err = new Stream(); +out.writable = err.writable = true; +out.write = err.write = function(d) {}; + +var c = new Console(out, err); + +out.write = err.write = function(d) { + assert.equal(d, 'test\n'); + called = true; +}; + +assert(!called); +c.log('test'); +assert(called); + +called = false; +c.error('test'); +assert(called); + +out.write = function(d) { + assert.equal('{ foo: 1 }\n', d); + called = true; +}; + +called = false; +c.dir({ foo: 1 }); +assert(called); + +// ensure that the console functions are bound to the console instance +called = 0; +out.write = function(d) { + called++; + assert.equal(d, called + ' ' + (called - 1) + ' [ 1, 2, 3 ]\n'); +}; +[1, 2, 3].forEach(c.log); +assert.equal(3, called); diff --git a/test/parallel/test-console-not-call-toString.js b/test/parallel/test-console-not-call-toString.js new file mode 100644 index 000000000..a62004f70 --- /dev/null +++ b/test/parallel/test-console-not-call-toString.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var func = function() {}; +var toStringCalled = false; +func.toString = function() { + toStringCalled = true; +}; + +require('util').inspect(func); + +assert.ok(!toStringCalled); diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js new file mode 100644 index 000000000..14ece8af5 --- /dev/null +++ b/test/parallel/test-console.js @@ -0,0 +1,82 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +assert.ok(process.stdout.writable); +assert.ok(process.stderr.writable); +// Support legacy API +assert.equal('number', typeof process.stdout.fd); +assert.equal('number', typeof process.stderr.fd); + +// an Object with a custom .inspect() function +var custom_inspect = { foo: 'bar', inspect: function () { return 'inspect'; } }; + +var stdout_write = global.process.stdout.write; +var strings = []; +global.process.stdout.write = function(string) { + strings.push(string); +}; +console._stderr = process.stdout; + +// test console.log() +console.log('foo'); +console.log('foo', 'bar'); +console.log('%s %s', 'foo', 'bar', 'hop'); +console.log({slashes: '\\\\'}); +console.log(custom_inspect); + +// test console.dir() +console.dir(custom_inspect); +console.dir(custom_inspect, { showHidden: false }); +console.dir({ foo : { bar : { baz : true } } }, { depth: 0 }); +console.dir({ foo : { bar : { baz : true } } }, { depth: 1 }); + +// test console.trace() +console.trace('This is a %j %d', { formatted: 'trace' }, 10, 'foo'); + + +global.process.stdout.write = stdout_write; + +assert.equal('foo\n', strings.shift()); +assert.equal('foo bar\n', strings.shift()); +assert.equal('foo bar hop\n', strings.shift()); +assert.equal("{ slashes: '\\\\\\\\' }\n", strings.shift()); +assert.equal('inspect\n', strings.shift()); +assert.equal("{ foo: 'bar', inspect: [Function] }\n", strings.shift()); +assert.equal("{ foo: 'bar', inspect: [Function] }\n", strings.shift()); +assert.notEqual(-1, strings.shift().indexOf('foo: [Object]')); +assert.equal(-1, strings.shift().indexOf('baz')); +assert.equal('Trace: This is a {"formatted":"trace"} 10 foo', + strings.shift().split('\n').shift()); + +assert.throws(function () { + console.timeEnd('no such label'); +}); + +assert.doesNotThrow(function () { + console.time('label'); + console.timeEnd('label'); +}); diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js new file mode 100644 index 000000000..8b4411607 --- /dev/null +++ b/test/parallel/test-crypto-authenticated.js @@ -0,0 +1,183 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + +// +// Test authenticated encryption modes. +// +// !NEVER USE STATIC IVs IN REAL LIFE! +// + +var TEST_CASES = [ + { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + iv: '583673497131313748307652', plain: 'Hello World!', + ct: '4BE13896F64DFA2C2D0F2C76', + tag: '272B422F62EB545EAA15B5FF84092447', tampered: false }, + { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + iv: '583673497131313748307652', plain: 'Hello World!', + ct: '4BE13896F64DFA2C2D0F2C76', aad: '000000FF', + tag: 'BA2479F66275665A88CB7B15F43EB005', tampered: false }, + { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + iv: '583673497131313748307652', plain: 'Hello World!', + ct: '4BE13596F64DFA2C2D0FAC76', + tag: '272B422F62EB545EAA15B5FF84092447', tampered: true }, + { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', + iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', + ct: '58E62CFE7B1D274111A82267EBB93866E72B6C2A', + tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: false }, + { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', + iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', + ct: '58E62CFF7B1D274011A82267EBB93866E72B6C2B', + tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: true }, + { algo: 'aes-192-gcm', key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', + iv: '0e1791e9db3bd21a9122c416', plain: 'Hello node.js world!', + password: 'very bad password', aad: '63616c76696e', + ct: 'DDA53A4059AA17B88756984995F7BBA3C636CC44', + tag: 'D2A35E5C611E5E3D2258360241C5B045', tampered: false } +]; + +var ciphers = crypto.getCiphers(); + +for (var i in TEST_CASES) { + var test = TEST_CASES[i]; + + if (ciphers.indexOf(test.algo) == -1) { + console.log('skipping unsupported ' + test.algo + ' test'); + continue; + } + + (function() { + var encrypt = crypto.createCipheriv(test.algo, + new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + if (test.aad) + encrypt.setAAD(new Buffer(test.aad, 'hex')); + var hex = encrypt.update(test.plain, 'ascii', 'hex'); + hex += encrypt.final('hex'); + var auth_tag = encrypt.getAuthTag(); + // only test basic encryption run if output is marked as tampered. + if (!test.tampered) { + assert.equal(hex.toUpperCase(), test.ct); + assert.equal(auth_tag.toString('hex').toUpperCase(), test.tag); + } + })(); + + (function() { + var decrypt = crypto.createDecipheriv(test.algo, + new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + decrypt.setAuthTag(new Buffer(test.tag, 'hex')); + if (test.aad) + decrypt.setAAD(new Buffer(test.aad, 'hex')); + var msg = decrypt.update(test.ct, 'hex', 'ascii'); + if (!test.tampered) { + msg += decrypt.final('ascii'); + assert.equal(msg, test.plain); + } else { + // assert that final throws if input data could not be verified! + assert.throws(function() { decrypt.final('ascii'); }, / auth/); + } + })(); + + (function() { + if (!test.password) return; + var encrypt = crypto.createCipher(test.algo, test.password); + if (test.aad) + encrypt.setAAD(new Buffer(test.aad, 'hex')); + var hex = encrypt.update(test.plain, 'ascii', 'hex'); + hex += encrypt.final('hex'); + var auth_tag = encrypt.getAuthTag(); + // only test basic encryption run if output is marked as tampered. + if (!test.tampered) { + assert.equal(hex.toUpperCase(), test.ct); + assert.equal(auth_tag.toString('hex').toUpperCase(), test.tag); + } + })(); + + (function() { + if (!test.password) return; + var decrypt = crypto.createDecipher(test.algo, test.password); + decrypt.setAuthTag(new Buffer(test.tag, 'hex')); + if (test.aad) + decrypt.setAAD(new Buffer(test.aad, 'hex')); + var msg = decrypt.update(test.ct, 'hex', 'ascii'); + if (!test.tampered) { + msg += decrypt.final('ascii'); + assert.equal(msg, test.plain); + } else { + // assert that final throws if input data could not be verified! + assert.throws(function() { decrypt.final('ascii'); }, / auth/); + } + })(); + + // after normal operation, test some incorrect ways of calling the API: + // it's most certainly enough to run these tests with one algorithm only. + + if (i > 0) { + continue; + } + + (function() { + // non-authenticating mode: + var encrypt = crypto.createCipheriv('aes-128-cbc', + 'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC'); + encrypt.update('blah', 'ascii'); + encrypt.final(); + assert.throws(function() { encrypt.getAuthTag(); }, / state/); + assert.throws(function() { + encrypt.setAAD(new Buffer('123', 'ascii')); }, / state/); + })(); + + (function() { + // trying to get tag before inputting all data: + var encrypt = crypto.createCipheriv(test.algo, + new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + encrypt.update('blah', 'ascii'); + assert.throws(function() { encrypt.getAuthTag(); }, / state/); + })(); + + (function() { + // trying to set tag on encryption object: + var encrypt = crypto.createCipheriv(test.algo, + new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + assert.throws(function() { + encrypt.setAuthTag(new Buffer(test.tag, 'hex')); }, / state/); + })(); + + (function() { + // trying to read tag from decryption object: + var decrypt = crypto.createDecipheriv(test.algo, + new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); + assert.throws(function() { decrypt.getAuthTag(); }, / state/); + })(); +} diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js new file mode 100644 index 000000000..fe7da668e --- /dev/null +++ b/test/parallel/test-crypto-binary-default.js @@ -0,0 +1,693 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This is the same as test/simple/test-crypto, but from before the shift +// to use buffers by default. + + +var common = require('../common'); +var assert = require('assert'); +var constants = require('constants'); + +try { + var crypto = require('crypto'); + var tls = require('tls'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'binary'; + +var fs = require('fs'); +var path = require('path'); + +// Test Certificates +var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); +var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); +var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); +var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', + 'ascii'); +var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', + 'ascii'); + +// TODO(indutny): Move to a separate test eventually +try { + var context = tls.createSecureContext({ + key: keyPem, + cert: certPem, + ca: caPem + }); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// PFX tests +assert.doesNotThrow(function() { + tls.createSecureContext({pfx:certPfx, passphrase:'sample'}); +}); + +assert.throws(function() { + tls.createSecureContext({pfx:certPfx}); +}, 'mac verify failure'); + +assert.throws(function() { + tls.createSecureContext({pfx:certPfx, passphrase:'test'}); +}, 'mac verify failure'); + +assert.throws(function() { + tls.createSecureContext({pfx:'sample', passphrase:'test'}); +}, 'not enough data'); + +// Test HMAC +var h1 = crypto.createHmac('sha1', 'Node') + .update('some data') + .update('to hmac') + .digest('hex'); +assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); + +// Test HMAC-SHA-* (rfc 4231 Test Cases) +var rfc4231 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: new Buffer('4869205468657265', 'hex'), // 'Hi There' + hmac: { + sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', + sha256: + 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + + '2e32cff7', + sha384: + 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + + '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', + sha512: + '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + + '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + + '2e696c203a126854' + } + }, + { + key: new Buffer('4a656665', 'hex'), // 'Jefe' + data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + + '96e673f', 'hex'), // 'what do ya want for nothing?' + hmac: { + sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', + sha256: + '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + + '64ec3843', + sha384: + 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + + '6322445e8e2240ca5e69e2c78b3239ecfab21649', + sha512: + '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + + 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + + '636e070a38bce737' + } + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', + 'hex'), + hmac: { + sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', + sha256: + '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + + 'ced565fe', + sha384: + '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + + '5966144b2a5ab39dc13814b94e3ab6e101a34f27', + sha512: + 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + + 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + + '74278859e13292fb' + } + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', + 'hex'), + hmac: { + sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', + sha256: + '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + + '6729665b', + sha384: + '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + + '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', + sha512: + 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + + '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + + 'e2adebeb10a298dd' + } + }, + + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + // 'Test With Truncation' + data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), + hmac: { + sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', + sha256: 'a3b6167473100ee06e0c796c2955552b', + sha384: '3abf34c3503b2a23a46efc619baef897', + sha512: '415fad6271580a531d4179bc891d87a6' + }, + truncate: true + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaa', 'hex'), + // 'Test Using Larger Than Block-Size Key - Hash Key First' + data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + + '4669727374', 'hex'), + hmac: { + sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', + sha256: + '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + + '0ee37f54', + sha384: + '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + + '033ac4c60c2ef6ab4030fe8296248df163f44952', + sha512: + '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + + '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + + '8b915a985d786598' + } + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaa', 'hex'), + // 'This is a test using a larger than block-size key and a larger ' + + // 'than block-size data. The key needs to be hashed before being ' + + // 'used by the HMAC algorithm.' + data: new Buffer('5468697320697320612074657374207573696e672061206c6' + + '172676572207468616e20626c6f636b2d73697a65206b6579' + + '20616e642061206c6172676572207468616e20626c6f636b2' + + 'd73697a6520646174612e20546865206b6579206e65656473' + + '20746f20626520686173686564206265666f7265206265696' + + 'e6720757365642062792074686520484d414320616c676f72' + + '6974686d2e', 'hex'), + hmac: { + sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', + sha256: + '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + + '5c3a35e2', + sha384: + '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + + '461e99c5a678cc31e799176d3860e6110c46523e', + sha512: + 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + + '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + + '65c97440fa8c6a58' + } + } +]; + +for (var i = 0, l = rfc4231.length; i < l; i++) { + for (var hash in rfc4231[i]['hmac']) { + var result = crypto.createHmac(hash, rfc4231[i]['key']) + .update(rfc4231[i]['data']) + .digest('hex'); + if (rfc4231[i]['truncate']) { + result = result.substr(0, 32); // first 128 bits == 32 hex chars + } + assert.equal(rfc4231[i]['hmac'][hash], + result, + 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); + } +} + +// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) +var rfc2202_md5 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: 'Hi There', + hmac: '9294727a3638bb1c13f48ef8158bfc9d' + }, + { + key: 'Jefe', + data: 'what do ya want for nothing?', + hmac: '750c783e6ab0b503eaa86e310a5db738' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', + 'hex'), + hmac: '56be34521d144c88dbb8c733f0e8b3f6' + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + + 'cdcdcdcdcd', + 'hex'), + hmac: '697eaf0aca3a3aea3a75164746ffaa79' + }, + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + data: 'Test With Truncation', + hmac: '56461ef2342edc00f9bab995690efd4c' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: 'Test Using Larger Than Block-Size Key - Hash Key First', + hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: + 'Test Using Larger Than Block-Size Key and Larger Than One ' + + 'Block-Size Data', + hmac: '6f630fad67cda0ee1fb1f562db3aa53e' + } +]; +var rfc2202_sha1 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: 'Hi There', + hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' + }, + { + key: 'Jefe', + data: 'what do ya want for nothing?', + hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddd' + + 'dddddddddd', + 'hex'), + hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + + 'cdcdcdcdcd', + 'hex'), + hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' + }, + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + data: 'Test With Truncation', + hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: 'Test Using Larger Than Block-Size Key - Hash Key First', + hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: + 'Test Using Larger Than Block-Size Key and Larger Than One ' + + 'Block-Size Data', + hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' + } +]; + +for (var i = 0, l = rfc2202_md5.length; i < l; i++) { + assert.equal(rfc2202_md5[i]['hmac'], + crypto.createHmac('md5', rfc2202_md5[i]['key']) + .update(rfc2202_md5[i]['data']) + .digest('hex'), + 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); +} +for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { + assert.equal(rfc2202_sha1[i]['hmac'], + crypto.createHmac('sha1', rfc2202_sha1[i]['key']) + .update(rfc2202_sha1[i]['data']) + .digest('hex'), + 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); +} + +// Test hashing +var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); +var a1 = crypto.createHash('md5').update('Test123').digest('binary'); +var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); +var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary +var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); + +assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); +assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + + '\u00bd\u008c', 'Test MD5 as binary'); +assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', + 'Test SHA256 as base64'); + +assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + + '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + + '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + + '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + + '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', + 'Test SHA512 as assumed binary'); + +assert.deepEqual(a4, + new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), + 'Test SHA1'); + +// Test multiple updates to same hash +var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); +var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); +assert.equal(h1, h2, 'multipled updates'); + +// Test hashing for binary files +var fn = path.join(common.fixturesDir, 'sample.png'); +var sha1Hash = crypto.createHash('sha1'); +var fileStream = fs.createReadStream(fn); +fileStream.on('data', function(data) { + sha1Hash.update(data); +}); +fileStream.on('close', function() { + assert.equal(sha1Hash.digest('hex'), + '22723e553129a336ad96e10f6aecdf0f45e4149e', + 'Test SHA1 of sample.png'); +}); + +// Issue #2227: unknown digest method should throw an error. +assert.throws(function() { + crypto.createHash('xyzzy'); +}); + +// Test signing and verifying +var s1 = crypto.createSign('RSA-SHA1') + .update('Test123') + .sign(keyPem, 'base64'); +var verified = crypto.createVerify('RSA-SHA1') + .update('Test') + .update('123') + .verify(certPem, s1, 'base64'); +assert.strictEqual(verified, true, 'sign and verify (base 64)'); + +var s2 = crypto.createSign('RSA-SHA256') + .update('Test123') + .sign(keyPem); // binary +var verified = crypto.createVerify('RSA-SHA256') + .update('Test') + .update('123') + .verify(certPem, s2); // binary +assert.strictEqual(verified, true, 'sign and verify (binary)'); + +var s3 = crypto.createSign('RSA-SHA1') + .update('Test123') + .sign(keyPem, 'buffer'); +var verified = crypto.createVerify('RSA-SHA1') + .update('Test') + .update('123') + .verify(certPem, s3); +assert.strictEqual(verified, true, 'sign and verify (buffer)'); + + +function testCipher1(key) { + // Test encryption and decryption + var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; + var cipher = crypto.createCipher('aes192', key); + + // encrypt plaintext which is in utf8 format + // to a ciphertext which will be in hex + var ciph = cipher.update(plaintext, 'utf8', 'hex'); + // Only use binary or hex, not base64. + ciph += cipher.final('hex'); + + var decipher = crypto.createDecipher('aes192', key); + var txt = decipher.update(ciph, 'hex', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption'); +} + + +function testCipher2(key) { + // encryption and decryption with Base64 + // reported in https://github.com/joyent/node/issues/738 + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipher('aes256', key); + + // encrypt plaintext which is in utf8 format + // to a ciphertext which will be in Base64 + var ciph = cipher.update(plaintext, 'utf8', 'base64'); + ciph += cipher.final('base64'); + + var decipher = crypto.createDecipher('aes256', key); + var txt = decipher.update(ciph, 'base64', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with Base64'); +} + + +function testCipher3(key, iv) { + // Test encyrption and decryption with explicit key and iv + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + var ciph = cipher.update(plaintext, 'utf8', 'hex'); + ciph += cipher.final('hex'); + + var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + var txt = decipher.update(ciph, 'hex', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); +} + + +function testCipher4(key, iv) { + // Test encyrption and decryption with explicit key and iv + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + var ciph = cipher.update(plaintext, 'utf8', 'buffer'); + ciph = Buffer.concat([ciph, cipher.final('buffer')]); + + var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + var txt = decipher.update(ciph, 'buffer', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); +} + + +testCipher1('MySecretKey123'); +testCipher1(new Buffer('MySecretKey123')); + +testCipher2('0123456789abcdef'); +testCipher2(new Buffer('0123456789abcdef')); + +testCipher3('0123456789abcd0123456789', '12345678'); +testCipher3('0123456789abcd0123456789', new Buffer('12345678')); +testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); +testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); + +testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); + + +// update() should only take buffers / strings +assert.throws(function() { + crypto.createHash('sha1').update({foo: 'bar'}); +}, /buffer/); + + +// Test Diffie-Hellman with two parties sharing a secret, +// using various encodings as we go along +var dh1 = crypto.createDiffieHellman(256); +var p1 = dh1.getPrime('buffer'); +var dh2 = crypto.createDiffieHellman(p1, 'base64'); +var key1 = dh1.generateKeys(); +var key2 = dh2.generateKeys('hex'); +var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); +var secret2 = dh2.computeSecret(key1, 'binary', 'buffer'); + +assert.equal(secret1, secret2.toString('base64')); + +// Create "another dh1" using generated keys from dh1, +// and compute secret again +var dh3 = crypto.createDiffieHellman(p1, 'buffer'); +var privkey1 = dh1.getPrivateKey(); +dh3.setPublicKey(key1); +dh3.setPrivateKey(privkey1); + +assert.equal(dh1.getPrime(), dh3.getPrime()); +assert.equal(dh1.getGenerator(), dh3.getGenerator()); +assert.equal(dh1.getPublicKey(), dh3.getPublicKey()); +assert.equal(dh1.getPrivateKey(), dh3.getPrivateKey()); + +var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); + +assert.equal(secret1, secret3); + +// https://github.com/joyent/node/issues/2338 +var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; +var d = crypto.createDiffieHellman(p, 'hex'); +assert.equal(d.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + +// Test RSA key signing/verification +var rsaSign = crypto.createSign('RSA-SHA1'); +var rsaVerify = crypto.createVerify('RSA-SHA1'); +assert.ok(rsaSign); +assert.ok(rsaVerify); + +rsaSign.update(rsaPubPem); +var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); +assert.equal(rsaSignature, + '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); + +rsaVerify.update(rsaPubPem); +assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); + + +// +// Test RSA signing and verification +// +(function() { + var privateKey = fs.readFileSync( + common.fixturesDir + '/test_rsa_privkey_2.pem'); + + var publicKey = fs.readFileSync( + common.fixturesDir + '/test_rsa_pubkey_2.pem'); + + var input = 'I AM THE WALRUS'; + + var signature = + '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + + '0ddfb299bedeb1ad'; + + var sign = crypto.createSign('RSA-SHA256'); + sign.update(input); + + var output = sign.sign(privateKey, 'hex'); + assert.equal(output, signature); + + var verify = crypto.createVerify('RSA-SHA256'); + verify.update(input); + + assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); +})(); + + +// +// Test DSA signing and verification +// +(function() { + var privateKey = fs.readFileSync( + common.fixturesDir + '/test_dsa_privkey.pem'); + + var publicKey = fs.readFileSync( + common.fixturesDir + '/test_dsa_pubkey.pem'); + + var input = 'I AM THE WALRUS'; + + // DSA signatures vary across runs so there is no static string to verify + // against + var sign = crypto.createSign('DSS1'); + sign.update(input); + var signature = sign.sign(privateKey, 'hex'); + + var verify = crypto.createVerify('DSS1'); + verify.update(input); + + assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); +})(); + + +// +// Test PBKDF2 with RFC 6070 test vectors (except #4) +// +function testPBKDF2(password, salt, iterations, keylen, expected) { + var actual = crypto.pbkdf2Sync(password, salt, iterations, keylen); + assert.equal(actual, expected); + + crypto.pbkdf2(password, salt, iterations, keylen, function(err, actual) { + assert.equal(actual, expected); + }); +} + + +testPBKDF2('password', 'salt', 1, 20, + '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + + '\xaf\x60\x12\x06\x2f\xe0\x37\xa6'); + +testPBKDF2('password', 'salt', 2, 20, + '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + + '\xce\x1d\x41\xf0\xd8\xde\x89\x57'); + +testPBKDF2('password', 'salt', 4096, 20, + '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + + '\xf7\x21\xd0\x65\xa4\x29\xc1'); + +testPBKDF2('passwordPASSWORDpassword', + 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + 4096, + 25, + '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + + '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38'); + +testPBKDF2('pass\0word', 'sa\0lt', 4096, 16, + '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + + '\x25\xe0\xc3'); diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js new file mode 100644 index 000000000..60fedee74 --- /dev/null +++ b/test/parallel/test-crypto-certificate.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var crypto = require('crypto'); + +crypto.DEFAULT_ENCODING = 'buffer'; + +var fs = require('fs'); +var path = require('path'); + +// Test Certificates +var spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); +var spkacFail = fs.readFileSync(common.fixturesDir + '/spkac.fail'); +var spkacPem = fs.readFileSync(common.fixturesDir + '/spkac.pem'); + +var certificate = new crypto.Certificate(); + +assert.equal(certificate.verifySpkac(spkacValid), true); +assert.equal(certificate.verifySpkac(spkacFail), false); + +assert.equal(stripLineEndings(certificate.exportPublicKey(spkacValid) + .toString('utf8')), + stripLineEndings(spkacPem.toString('utf8'))); +assert.equal(certificate.exportPublicKey(spkacFail), ''); + +assert.equal(certificate.exportChallenge(spkacValid) + .toString('utf8'), + 'fb9ab814-6677-42a4-a60c-f905d1a6924d'); +assert.equal(certificate.exportChallenge(spkacFail), ''); + +function stripLineEndings(obj) { + return obj.replace(/\n/g, ''); +} diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js new file mode 100644 index 000000000..a3d99e9b5 --- /dev/null +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var crypto = require('crypto'); +var odd = new Buffer(39); +odd.fill('A'); + +var c = crypto.createDiffieHellman(32); +c.setPrivateKey(odd); +c.generateKeys(); diff --git a/test/parallel/test-crypto-domain.js b/test/parallel/test-crypto-domain.js new file mode 100644 index 000000000..6284afc07 --- /dev/null +++ b/test/parallel/test-crypto-domain.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Skipping test, compiled without crypto support.'); + return; +} + +function test(fn) { + var ex = new Error('BAM'); + var d = domain.create(); + d.on('error', common.mustCall(function(err) { + assert.equal(err, ex); + })); + var cb = common.mustCall(function() { + throw ex; + }); + d.run(cb); +} + +test(function(cb) { + crypto.pbkdf2('password', 'salt', 1, 8, cb); +}); + +test(function(cb) { + crypto.randomBytes(32, cb); +}); diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js new file mode 100644 index 000000000..1393f6da1 --- /dev/null +++ b/test/parallel/test-crypto-domains.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. + +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: + +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var crypto = require('crypto'); +var domain = require('domain'); +var assert = require('assert'); +var d = domain.create(); +var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes'] +var errors = 0; + +process.on('exit', function() { + assert.equal(errors, 3); +}); + +d.on('error', function (e) { + assert.equal(e.message, expect.shift()); + errors += 1; +}); + +d.run(function () { + one(); + + function one() { + crypto.pbkdf2('a', 'b', 1, 8, function () { + two(); + throw new Error('pbkdf2'); + }); + } + + function two() { + crypto.randomBytes(4, function () { + three(); + throw new Error('randomBytes'); + }); + } + + function three() { + crypto.pseudoRandomBytes(4, function () { + throw new Error('pseudoRandomBytes'); + }); + } +}); diff --git a/test/parallel/test-crypto-ecb.js b/test/parallel/test-crypto-ecb.js new file mode 100644 index 000000000..e5b893cfc --- /dev/null +++ b/test/parallel/test-crypto-ecb.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + +// Testing whether EVP_CipherInit_ex is functioning correctly. +// Reference: bug#1997 + +(function() { + var encrypt = crypto.createCipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', ''); + var hex = encrypt.update('Hello World!', 'ascii', 'hex'); + hex += encrypt.final('hex'); + assert.equal(hex.toUpperCase(), '6D385F424AAB0CFBF0BB86E07FFB7D71'); +}()); + +(function() { + var decrypt = crypto.createDecipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', + ''); + var msg = decrypt.update('6D385F424AAB0CFBF0BB86E07FFB7D71', 'hex', 'ascii'); + msg += decrypt.final('ascii'); + assert.equal(msg, 'Hello World!'); +}()); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js new file mode 100644 index 000000000..203361700 --- /dev/null +++ b/test/parallel/test-crypto-from-binary.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This is the same as test/simple/test-crypto, but from before the shift +// to use buffers by default. + + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +var EXTERN_APEX = 0xFBEE9; + +// manually controlled string for checking binary output +var ucs2_control = 'a\u0000'; + +// grow the strings to proper length +while (ucs2_control.length <= EXTERN_APEX) { + ucs2_control += ucs2_control; +} + + +// check resultant buffer and output string +var b = new Buffer(ucs2_control + ucs2_control, 'ucs2'); + +// +// Test updating from birant data +// +(function() { + var datum1 = b.slice(700000); + var hash1_converted = crypto.createHash('sha1') + .update(datum1.toString('base64'), 'base64') + .digest('hex'); + var hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); + assert.equal(hash1_direct, hash1_converted, 'should hash the same.'); + + var datum2 = b; + var hash2_converted = crypto.createHash('sha1') + .update(datum2.toString('base64'), 'base64') + .digest('hex'); + var hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); + assert.equal(hash2_direct, hash2_converted, 'should hash the same.'); +})(); diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js new file mode 100644 index 000000000..1394903fa --- /dev/null +++ b/test/parallel/test-crypto-hash-stream-pipe.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var crypto = require('crypto'); +var stream = require('stream') +var s = new stream.PassThrough(); +var h = crypto.createHash('sha1'); +var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; +var gotData = false; + +process.on('exit', function() { + assert(gotData); + console.log('ok'); +}); + +s.pipe(h).on('data', function(c) { + assert.equal(c, expect); + gotData = true; +}).setEncoding('hex'); + +s.end('aoeu'); diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js new file mode 100644 index 000000000..dd293feb1 --- /dev/null +++ b/test/parallel/test-crypto-padding-aes256.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OpenSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + +function aes256(decipherFinal) { + var iv = new Buffer('00000000000000000000000000000000', 'hex'); + var key = new Buffer('0123456789abcdef0123456789abcdef' + + '0123456789abcdef0123456789abcdef', 'hex'); + + function encrypt(val, pad) { + var c = crypto.createCipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'utf8', 'binary') + c.final('binary'); + } + + function decrypt(val, pad) { + var c = crypto.createDecipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); + } + + // echo 0123456789abcdef0123456789abcdef \ + // | openssl enc -e -aes256 -nopad -K -iv \ + // | openssl enc -d -aes256 -nopad -K -iv + var plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size + var encrypted = encrypt(plaintext, false); + var decrypted = decrypt(encrypted, false); + assert.equal(decrypted, plaintext); + + // echo 0123456789abcdef0123456789abcde \ + // | openssl enc -e -aes256 -K -iv \ + // | openssl enc -d -aes256 -K -iv + plaintext = '0123456789abcdef0123456789abcde'; // not a multiple + encrypted = encrypt(plaintext, true); + decrypted = decrypt(encrypted, true); + assert.equal(decrypted, plaintext); +} + +aes256('final'); +aes256('finaltol'); diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js new file mode 100644 index 000000000..22edbf481 --- /dev/null +++ b/test/parallel/test-crypto-padding.js @@ -0,0 +1,132 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + + +/* + * Input data + */ + +var ODD_LENGTH_PLAIN = 'Hello node world!', + EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi'; + +var KEY_PLAIN = 'S3c.r.e.t.K.e.Y!', + IV_PLAIN = 'blahFizz2011Buzz'; + +var CIPHER_NAME = 'aes-128-cbc'; + + +/* + * Expected result data + */ + +// echo -n 'Hello node world!' | \ +// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ +// -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 +var ODD_LENGTH_ENCRYPTED = + '7f57859550d4d2fdb9806da2a750461a9fe77253cd1cbd4b07beee4e070d561f'; + +// echo -n 'Hello node world!AbC09876dDeFgHi' | \ +// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ +// -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 +var EVEN_LENGTH_ENCRYPTED = + '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b988' + + '6119866912cb8c7bcaf76c5ebc2378'; + +// echo -n 'Hello node world!AbC09876dDeFgHi' | \ +// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ +// -iv 626c616846697a7a3230313142757a7a -nopad | xxd -p -c256 +var EVEN_LENGTH_ENCRYPTED_NOPAD = + '7f57859550d4d2fdb9806da2a750461ab46e' + + '71b3d78ebe2d9684dfc87f7575b9'; + + +/* + * Helper wrappers + */ + +function enc(plain, pad) { + var encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); + encrypt.setAutoPadding(pad); + var hex = encrypt.update(plain, 'ascii', 'hex'); + hex += encrypt.final('hex'); + return hex; +} + +function dec(encd, pad) { + var decrypt = crypto.createDecipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); + decrypt.setAutoPadding(pad); + var plain = decrypt.update(encd, 'hex'); + plain += decrypt.final('binary'); + return plain; +} + + +/* + * Test encryption + */ + +assert.equal(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED); +assert.equal(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED); + +assert.throws(function() { + // input must have block length % + enc(ODD_LENGTH_PLAIN, false); +}); + +assert.doesNotThrow(function() { + assert.equal(enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD); +}); + + +/* + * Test decryption + */ + +assert.equal(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN); +assert.equal(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN); + +assert.doesNotThrow(function() { + // returns including original padding + assert.equal(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); + assert.equal(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); +}); + +assert.throws(function() { + // must have at least 1 byte of padding (PKCS): + assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN); +}); + +assert.doesNotThrow(function() { + // no-pad encrypted string should return the same: + assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN); +}); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js new file mode 100644 index 000000000..24a76f4f1 --- /dev/null +++ b/test/parallel/test-crypto-random.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + +// bump, we register a lot of exit listeners +process.setMaxListeners(256); + +[crypto.randomBytes, + crypto.pseudoRandomBytes +].forEach(function(f) { + [-1, + undefined, + null, + false, + true, + {}, + [] + ].forEach(function(value) { + assert.throws(function() { f(value); }); + assert.throws(function() { f(value, function() {}); }); + }); + + [0, 1, 2, 4, 16, 256, 1024].forEach(function(len) { + f(len, checkCall(function(ex, buf) { + assert.equal(null, ex); + assert.equal(len, buf.length); + assert.ok(Buffer.isBuffer(buf)); + })); + }); +}); + +// assert that the callback is indeed called +function checkCall(cb, desc) { + var called_ = false; + + process.on('exit', function() { + assert.equal(true, called_, desc || ('callback not called: ' + cb)); + }); + + return function() { + return called_ = true, cb.apply(cb, Array.prototype.slice.call(arguments)); + }; +} + +// #5126, "FATAL ERROR: v8::Object::SetIndexedPropertiesToExternalArrayData() +// length exceeds max acceptable value" +assert.throws(function() { + crypto.randomBytes(0x3fffffff + 1); +}, TypeError); diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js new file mode 100644 index 000000000..ff58e8040 --- /dev/null +++ b/test/parallel/test-crypto-stream.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var stream = require('stream'); +var util = require('util'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// Small stream to buffer converter +function Stream2buffer(callback) { + stream.Writable.call(this); + + this._buffers = []; + this.once('finish', function () { + callback(null, Buffer.concat(this._buffers)); + }); +} +util.inherits(Stream2buffer, stream.Writable); + +Stream2buffer.prototype._write = function (data, encodeing, done) { + this._buffers.push(data); + return done(null); +}; + +// Create an md5 hash of "Hallo world" +var hasher1 = crypto.createHash('md5'); + hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { + assert.equal(err, null); + assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); + }))); + hasher1.end('Hallo world'); + +// Simpler check for unpipe, setEncoding, pause and resume +crypto.createHash('md5').unpipe({}); +crypto.createHash('md5').setEncoding('utf8'); +crypto.createHash('md5').pause(); +crypto.createHash('md5').resume(); + +// Decipher._flush() should emit an error event, not an exception. +var key = new Buffer('48fb56eb10ffeb13fc0ef551bbca3b1b', 'hex'), + badkey = new Buffer('12341234123412341234123412341234', 'hex'), + iv = new Buffer('6d358219d1f488f5f4eb12820a66d146', 'hex'), + cipher = crypto.createCipheriv('aes-128-cbc', key, iv), + decipher = crypto.createDecipheriv('aes-128-cbc', badkey, iv); + +cipher.pipe(decipher) + .on('error', common.mustCall(function end(err) { + assert(/Unsupported/.test(err)); + })); + +cipher.end('Papaya!'); // Should not cause an unhandled exception. diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js new file mode 100644 index 000000000..09c43ddc0 --- /dev/null +++ b/test/parallel/test-crypto-verify-failure.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); + var tls = require('tls'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + +var fs = require('fs'); + +var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var canSend = true; + +var server = tls.Server(options, function(socket) { + setImmediate(function() { + console.log('sending'); + verify(); + setImmediate(function() { + socket.destroy(); + }); + }); +}); + +var client; + +function verify() { + console.log('verify'); + var verified = crypto.createVerify('RSA-SHA1') + .update('Test') + .verify(certPem, 'asdfasdfas', 'base64'); +} + +server.listen(common.PORT, function() { + client = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + verify(); + }).on('data', function(data) { + console.log(data); + }).on('error', function(err) { + throw err; + }).on('close', function() { + server.close(); + }).resume(); +}); + +server.unref(); diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js new file mode 100644 index 000000000..d3f1ade32 --- /dev/null +++ b/test/parallel/test-crypto.js @@ -0,0 +1,1220 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +crypto.DEFAULT_ENCODING = 'buffer'; + +var fs = require('fs'); +var path = require('path'); +var constants = require('constants'); + +// Test Certificates +var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); +var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); +var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); +var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); +var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', + 'ascii'); +var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', + 'ascii'); +var rsaKeyPemEncrypted = fs.readFileSync( + common.fixturesDir + '/test_rsa_privkey_encrypted.pem', 'ascii'); +var dsaPubPem = fs.readFileSync(common.fixturesDir + '/test_dsa_pubkey.pem', + 'ascii'); +var dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem', + 'ascii'); +var dsaKeyPemEncrypted = fs.readFileSync( + common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); + + +// TODO(indunty): move to a separate test eventually +try { + var tls = require('tls'); + var context = tls.createSecureContext({ + key: keyPem, + cert: certPem, + ca: caPem + }); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// 'this' safety +// https://github.com/joyent/node/issues/6690 +assert.throws(function() { + var options = {key: keyPem, cert: certPem, ca: caPem}; + var credentials = crypto.createCredentials(options); + var context = credentials.context; + var notcontext = { setOptions: context.setOptions, setKey: context.setKey }; + crypto.createCredentials({ secureOptions: 1 }, notcontext); +}, TypeError); + +// PFX tests +assert.doesNotThrow(function() { + tls.createSecureContext({pfx:certPfx, passphrase:'sample'}); +}); + +assert.throws(function() { + tls.createSecureContext({pfx:certPfx}); +}, 'mac verify failure'); + +assert.throws(function() { + tls.createSecureContext({pfx:certPfx, passphrase:'test'}); +}, 'mac verify failure'); + +assert.throws(function() { + tls.createSecureContext({pfx:'sample', passphrase:'test'}); +}, 'not enough data'); + +// Test HMAC +var h1 = crypto.createHmac('sha1', 'Node') + .update('some data') + .update('to hmac') + .digest('hex'); +assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); + +// Test HMAC (Wikipedia Test Cases) +var wikipedia = [ + { + key: 'key', data: 'The quick brown fox jumps over the lazy dog', + hmac: { // HMACs lifted from Wikipedia. + md5: '80070713463e7749b90c2dc24911e275', + sha1: 'de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9', + sha256: + 'f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc' + + '2d1a3cd8' + } + }, + { + key: 'key', data: '', + hmac: { // Intermediate test to help debugging. + md5: '63530468a04e386459855da0063b6596', + sha1: 'f42bb0eeb018ebbd4597ae7213711ec60760843f', + sha256: + '5d5d139563c95b5967b9bd9a8c9b233a9dedb45072794cd232dc1b74' + + '832607d0' + } + }, + { + key: '', data: 'The quick brown fox jumps over the lazy dog', + hmac: { // Intermediate test to help debugging. + md5: 'ad262969c53bc16032f160081c4a07a0', + sha1: '2ba7f707ad5f187c412de3106583c3111d668de8', + sha256: + 'fb011e6154a19b9a4c767373c305275a5a69e8b68b0b4c9200c383dc' + + 'ed19a416' + } + }, + { + key: '', data: '', + hmac: { // HMACs lifted from Wikipedia. + md5: '74e6f7298a9c2d168935f58c001bad88', + sha1: 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', + sha256: + 'b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c71214' + + '4292c5ad' + } + }, +] + +for (var i = 0, l = wikipedia.length; i < l; i++) { + for (var hash in wikipedia[i]['hmac']) { + var result = crypto.createHmac(hash, wikipedia[i]['key']) + .update(wikipedia[i]['data']) + .digest('hex'); + assert.equal(wikipedia[i]['hmac'][hash], + result, + 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' wikipedia'); + } +} + + +// Test HMAC-SHA-* (rfc 4231 Test Cases) +var rfc4231 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: new Buffer('4869205468657265', 'hex'), // 'Hi There' + hmac: { + sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', + sha256: + 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + + '2e32cff7', + sha384: + 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + + '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', + sha512: + '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + + '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + + '2e696c203a126854' + } + }, + { + key: new Buffer('4a656665', 'hex'), // 'Jefe' + data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + + '96e673f', 'hex'), // 'what do ya want for nothing?' + hmac: { + sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', + sha256: + '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + + '64ec3843', + sha384: + 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + + '6322445e8e2240ca5e69e2c78b3239ecfab21649', + sha512: + '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + + 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + + '636e070a38bce737' + } + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', + 'hex'), + hmac: { + sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', + sha256: + '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + + 'ced565fe', + sha384: + '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + + '5966144b2a5ab39dc13814b94e3ab6e101a34f27', + sha512: + 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + + 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + + '74278859e13292fb' + } + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', + 'hex'), + hmac: { + sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', + sha256: + '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + + '6729665b', + sha384: + '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + + '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', + sha512: + 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + + '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + + 'e2adebeb10a298dd' + } + }, + + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + // 'Test With Truncation' + data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), + hmac: { + sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', + sha256: 'a3b6167473100ee06e0c796c2955552b', + sha384: '3abf34c3503b2a23a46efc619baef897', + sha512: '415fad6271580a531d4179bc891d87a6' + }, + truncate: true + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaa', 'hex'), + // 'Test Using Larger Than Block-Size Key - Hash Key First' + data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + + 'c6f636b2d53697a65204b6579202d2048617368204b657920' + + '4669727374', 'hex'), + hmac: { + sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', + sha256: + '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + + '0ee37f54', + sha384: + '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + + '033ac4c60c2ef6ab4030fe8296248df163f44952', + sha512: + '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + + '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + + '8b915a985d786598' + } + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaa', 'hex'), + // 'This is a test using a larger than block-size key and a larger ' + + // 'than block-size data. The key needs to be hashed before being ' + + // 'used by the HMAC algorithm.' + data: new Buffer('5468697320697320612074657374207573696e672061206c6' + + '172676572207468616e20626c6f636b2d73697a65206b6579' + + '20616e642061206c6172676572207468616e20626c6f636b2' + + 'd73697a6520646174612e20546865206b6579206e65656473' + + '20746f20626520686173686564206265666f7265206265696' + + 'e6720757365642062792074686520484d414320616c676f72' + + '6974686d2e', 'hex'), + hmac: { + sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', + sha256: + '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + + '5c3a35e2', + sha384: + '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + + '461e99c5a678cc31e799176d3860e6110c46523e', + sha512: + 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + + '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + + '65c97440fa8c6a58' + } + } +]; + +for (var i = 0, l = rfc4231.length; i < l; i++) { + for (var hash in rfc4231[i]['hmac']) { + var str = crypto.createHmac(hash, rfc4231[i].key); + str.end(rfc4231[i].data); + var strRes = str.read().toString('hex'); + var result = crypto.createHmac(hash, rfc4231[i]['key']) + .update(rfc4231[i]['data']) + .digest('hex'); + if (rfc4231[i]['truncate']) { + result = result.substr(0, 32); // first 128 bits == 32 hex chars + strRes = strRes.substr(0, 32); + } + assert.equal(rfc4231[i]['hmac'][hash], + result, + 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); + assert.equal(strRes, result, 'Should get same result from stream'); + } +} + +// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) +var rfc2202_md5 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: 'Hi There', + hmac: '9294727a3638bb1c13f48ef8158bfc9d' + }, + { + key: 'Jefe', + data: 'what do ya want for nothing?', + hmac: '750c783e6ab0b503eaa86e310a5db738' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', + 'hex'), + hmac: '56be34521d144c88dbb8c733f0e8b3f6' + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + + 'cdcdcdcdcd', + 'hex'), + hmac: '697eaf0aca3a3aea3a75164746ffaa79' + }, + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + data: 'Test With Truncation', + hmac: '56461ef2342edc00f9bab995690efd4c' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: 'Test Using Larger Than Block-Size Key - Hash Key First', + hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: + 'Test Using Larger Than Block-Size Key and Larger Than One ' + + 'Block-Size Data', + hmac: '6f630fad67cda0ee1fb1f562db3aa53e' + } +]; +var rfc2202_sha1 = [ + { + key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), + data: 'Hi There', + hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' + }, + { + key: 'Jefe', + data: 'what do ya want for nothing?', + hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), + data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + + 'ddddddddddddddddddddddddddddddddddddddddddddd' + + 'dddddddddd', + 'hex'), + hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' + }, + { + key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', + 'hex'), + data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + + 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + + 'cdcdcdcdcd', + 'hex'), + hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' + }, + { + key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), + data: 'Test With Truncation', + hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: 'Test Using Larger Than Block-Size Key - Hash Key First', + hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' + }, + { + key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + + 'aaaaaaaaaaaaaaaaaaaaaa', + 'hex'), + data: + 'Test Using Larger Than Block-Size Key and Larger Than One ' + + 'Block-Size Data', + hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' + } +]; + +for (var i = 0, l = rfc2202_md5.length; i < l; i++) { + assert.equal(rfc2202_md5[i]['hmac'], + crypto.createHmac('md5', rfc2202_md5[i]['key']) + .update(rfc2202_md5[i]['data']) + .digest('hex'), + 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); +} +for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { + assert.equal(rfc2202_sha1[i]['hmac'], + crypto.createHmac('sha1', rfc2202_sha1[i]['key']) + .update(rfc2202_sha1[i]['data']) + .digest('hex'), + 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); +} + +// Test hashing +var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); +var a1 = crypto.createHash('md5').update('Test123').digest('binary'); +var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); +var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary +var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); + +// stream interface +var a5 = crypto.createHash('sha512'); +a5.end('Test123'); +a5 = a5.read(); + +var a6 = crypto.createHash('sha512'); +a6.write('Te'); +a6.write('st'); +a6.write('123'); +a6.end(); +a6 = a6.read(); + +var a7 = crypto.createHash('sha512'); +a7.end(); +a7 = a7.read(); + +var a8 = crypto.createHash('sha512'); +a8.write(''); +a8.end(); +a8 = a8.read(); + +assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); +assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + + '\u00bd\u008c', 'Test MD5 as binary'); +assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', + 'Test SHA256 as base64'); +assert.deepEqual( + a3, + new Buffer( + '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + + '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + + '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + + '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + + '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', + 'binary'), + 'Test SHA512 as assumed buffer'); +assert.deepEqual(a4, + new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), + 'Test SHA1'); + +// stream interface should produce the same result. +assert.deepEqual(a5, a3, 'stream interface is consistent'); +assert.deepEqual(a6, a3, 'stream interface is consistent'); +assert.notEqual(a7, undefined, 'no data should return data'); +assert.notEqual(a8, undefined, 'empty string should generate data'); + +// Test multiple updates to same hash +var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); +var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); +assert.equal(h1, h2, 'multipled updates'); + +// Test hashing for binary files +var fn = path.join(common.fixturesDir, 'sample.png'); +var sha1Hash = crypto.createHash('sha1'); +var fileStream = fs.createReadStream(fn); +fileStream.on('data', function(data) { + sha1Hash.update(data); +}); +fileStream.on('close', function() { + assert.equal(sha1Hash.digest('hex'), + '22723e553129a336ad96e10f6aecdf0f45e4149e', + 'Test SHA1 of sample.png'); +}); + +// Issue #2227: unknown digest method should throw an error. +assert.throws(function() { + crypto.createHash('xyzzy'); +}); + +// Test signing and verifying +var s1 = crypto.createSign('RSA-SHA1') + .update('Test123') + .sign(keyPem, 'base64'); +var s1stream = crypto.createSign('RSA-SHA1'); +s1stream.end('Test123'); +s1stream = s1stream.sign(keyPem, 'base64'); +assert.equal(s1, s1stream, 'Stream produces same output'); + +var verified = crypto.createVerify('RSA-SHA1') + .update('Test') + .update('123') + .verify(certPem, s1, 'base64'); +assert.strictEqual(verified, true, 'sign and verify (base 64)'); + +var s2 = crypto.createSign('RSA-SHA256') + .update('Test123') + .sign(keyPem, 'binary'); +var s2stream = crypto.createSign('RSA-SHA256'); +s2stream.end('Test123'); +s2stream = s2stream.sign(keyPem, 'binary'); +assert.equal(s2, s2stream, 'Stream produces same output'); + +var verified = crypto.createVerify('RSA-SHA256') + .update('Test') + .update('123') + .verify(certPem, s2, 'binary'); +assert.strictEqual(verified, true, 'sign and verify (binary)'); + +var verStream = crypto.createVerify('RSA-SHA256'); +verStream.write('Tes'); +verStream.write('t12'); +verStream.end('3'); +verified = verStream.verify(certPem, s2, 'binary'); +assert.strictEqual(verified, true, 'sign and verify (stream)'); + +var s3 = crypto.createSign('RSA-SHA1') + .update('Test123') + .sign(keyPem, 'buffer'); +var verified = crypto.createVerify('RSA-SHA1') + .update('Test') + .update('123') + .verify(certPem, s3); +assert.strictEqual(verified, true, 'sign and verify (buffer)'); + +var verStream = crypto.createVerify('RSA-SHA1'); +verStream.write('Tes'); +verStream.write('t12'); +verStream.end('3'); +verified = verStream.verify(certPem, s3); +assert.strictEqual(verified, true, 'sign and verify (stream)'); + + +function testCipher1(key) { + // Test encryption and decryption + var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; + var cipher = crypto.createCipher('aes192', key); + + // encrypt plaintext which is in utf8 format + // to a ciphertext which will be in hex + var ciph = cipher.update(plaintext, 'utf8', 'hex'); + // Only use binary or hex, not base64. + ciph += cipher.final('hex'); + + var decipher = crypto.createDecipher('aes192', key); + var txt = decipher.update(ciph, 'hex', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption'); + + // streaming cipher interface + // NB: In real life, it's not guaranteed that you can get all of it + // in a single read() like this. But in this case, we know it's + // quite small, so there's no harm. + var cStream = crypto.createCipher('aes192', key); + cStream.end(plaintext); + ciph = cStream.read(); + + var dStream = crypto.createDecipher('aes192', key); + dStream.end(ciph); + txt = dStream.read().toString('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with streams'); +} + + +function testCipher2(key) { + // encryption and decryption with Base64 + // reported in https://github.com/joyent/node/issues/738 + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipher('aes256', key); + + // encrypt plaintext which is in utf8 format + // to a ciphertext which will be in Base64 + var ciph = cipher.update(plaintext, 'utf8', 'base64'); + ciph += cipher.final('base64'); + + var decipher = crypto.createDecipher('aes256', key); + var txt = decipher.update(ciph, 'base64', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with Base64'); +} + + +function testCipher3(key, iv) { + // Test encyrption and decryption with explicit key and iv + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + var ciph = cipher.update(plaintext, 'utf8', 'hex'); + ciph += cipher.final('hex'); + + var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + var txt = decipher.update(ciph, 'hex', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); + + // streaming cipher interface + // NB: In real life, it's not guaranteed that you can get all of it + // in a single read() like this. But in this case, we know it's + // quite small, so there's no harm. + var cStream = crypto.createCipheriv('des-ede3-cbc', key, iv); + cStream.end(plaintext); + ciph = cStream.read(); + + var dStream = crypto.createDecipheriv('des-ede3-cbc', key, iv); + dStream.end(ciph); + txt = dStream.read().toString('utf8'); + + assert.equal(txt, plaintext, 'streaming cipher iv'); +} + + +function testCipher4(key, iv) { + // Test encyrption and decryption with explicit key and iv + var plaintext = + '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + + 'jAfaFg**'; + var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); + var ciph = cipher.update(plaintext, 'utf8', 'buffer'); + ciph = Buffer.concat([ciph, cipher.final('buffer')]); + + var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); + var txt = decipher.update(ciph, 'buffer', 'utf8'); + txt += decipher.final('utf8'); + + assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); +} + + +testCipher1('MySecretKey123'); +testCipher1(new Buffer('MySecretKey123')); + +testCipher2('0123456789abcdef'); +testCipher2(new Buffer('0123456789abcdef')); + +testCipher3('0123456789abcd0123456789', '12345678'); +testCipher3('0123456789abcd0123456789', new Buffer('12345678')); +testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); +testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); + +testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); + + +// update() should only take buffers / strings +assert.throws(function() { + crypto.createHash('sha1').update({foo: 'bar'}); +}, /buffer/); + + +// Test Diffie-Hellman with two parties sharing a secret, +// using various encodings as we go along +var dh1 = crypto.createDiffieHellman(256); +var p1 = dh1.getPrime('buffer'); +var dh2 = crypto.createDiffieHellman(p1, 'buffer'); +var key1 = dh1.generateKeys(); +var key2 = dh2.generateKeys('hex'); +var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); +var secret2 = dh2.computeSecret(key1, 'binary', 'buffer'); + +assert.equal(secret1, secret2.toString('base64')); +assert.equal(dh1.verifyError, 0); +assert.equal(dh2.verifyError, 0); + +assert.throws(function() { + crypto.createDiffieHellman([0x1, 0x2]); +}); + +assert.throws(function() { + crypto.createDiffieHellman(function() { }); +}); + +assert.throws(function() { + crypto.createDiffieHellman(/abc/); +}); + +assert.throws(function() { + crypto.createDiffieHellman({}); +}); + +// Create "another dh1" using generated keys from dh1, +// and compute secret again +var dh3 = crypto.createDiffieHellman(p1, 'buffer'); +var privkey1 = dh1.getPrivateKey(); +dh3.setPublicKey(key1); +dh3.setPrivateKey(privkey1); + +assert.deepEqual(dh1.getPrime(), dh3.getPrime()); +assert.deepEqual(dh1.getGenerator(), dh3.getGenerator()); +assert.deepEqual(dh1.getPublicKey(), dh3.getPublicKey()); +assert.deepEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); +assert.equal(dh3.verifyError, 0); + +var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); + +assert.equal(secret1, secret3); + +// Run this one twice to make sure that the dh3 clears its error properly +(function() { + var c = crypto.createDecipher('aes-128-ecb', ''); + assert.throws(function() { c.final('utf8') }, /wrong final block length/); +})(); + +assert.throws(function() { + dh3.computeSecret(''); +}, /key is too small/i); + +(function() { + var c = crypto.createDecipher('aes-128-ecb', ''); + assert.throws(function() { c.final('utf8') }, /wrong final block length/); +})(); + +// Create a shared using a DH group. +var alice = crypto.createDiffieHellmanGroup('modp5'); +var bob = crypto.createDiffieHellmanGroup('modp5'); +alice.generateKeys(); +bob.generateKeys(); +var aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); +var bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); +assert.equal(aSecret, bSecret); +assert.equal(alice.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); +assert.equal(bob.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + +// Ensure specific generator (buffer) works as expected. +var modp1 = crypto.createDiffieHellmanGroup('modp1'); +var modp1buf = new Buffer([ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, + 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, + 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, + 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, + 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, + 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, + 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, + 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, + 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff +]); +var exmodp1 = crypto.createDiffieHellman(modp1buf, new Buffer([2])); +modp1.generateKeys(); +exmodp1.generateKeys(); +var modp1Secret = modp1.computeSecret(exmodp1.getPublicKey()).toString('hex'); +var exmodp1Secret = exmodp1.computeSecret(modp1.getPublicKey()).toString('hex'); +assert.equal(modp1Secret, exmodp1Secret); +assert.equal(modp1.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); +assert.equal(exmodp1.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + + +// Ensure specific generator (string with encoding) works as expected. +var exmodp1_2 = crypto.createDiffieHellman(modp1buf, '02', 'hex'); +exmodp1_2.generateKeys(); +modp1Secret = modp1.computeSecret(exmodp1_2.getPublicKey()).toString('hex'); +var exmodp1_2Secret = exmodp1_2.computeSecret(modp1.getPublicKey()) + .toString('hex'); +assert.equal(modp1Secret, exmodp1_2Secret); +assert.equal(exmodp1_2.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + + +// Ensure specific generator (string without encoding) works as expected. +var exmodp1_3 = crypto.createDiffieHellman(modp1buf, '\x02'); +exmodp1_3.generateKeys(); +modp1Secret = modp1.computeSecret(exmodp1_3.getPublicKey()).toString('hex'); +var exmodp1_3Secret = exmodp1_3.computeSecret(modp1.getPublicKey()) + .toString('hex'); +assert.equal(modp1Secret, exmodp1_3Secret); +assert.equal(exmodp1_3.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + + +// Ensure specific generator (numeric) works as expected. +var exmodp1_4 = crypto.createDiffieHellman(modp1buf, 2); +exmodp1_4.generateKeys(); +modp1Secret = modp1.computeSecret(exmodp1_4.getPublicKey()).toString('hex'); +var exmodp1_4Secret = exmodp1_4.computeSecret(modp1.getPublicKey()) + .toString('hex'); +assert.equal(modp1Secret, exmodp1_4Secret); +assert.equal(exmodp1_4.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + + +var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; +var bad_dh = crypto.createDiffieHellman(p, 'hex'); +assert.equal(bad_dh.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); + +// Test RSA encryption/decryption +(function() { + var input = 'I AM THE WALRUS'; + var bufferToEncrypt = new Buffer(input); + + var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); + + var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); + assert.equal(input, decryptedBuffer.toString()); + + var decryptedBufferWithPassword = crypto.privateDecrypt({ + key: rsaKeyPemEncrypted, + passphrase: 'password' + }, encryptedBuffer); + assert.equal(input, decryptedBufferWithPassword.toString()); + + encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); + + decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); + assert.equal(input, decryptedBuffer.toString()); + + encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); + + decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); + assert.equal(input, decryptedBuffer.toString()); + + assert.throws(function() { + crypto.privateDecrypt({ + key: rsaKeyPemEncrypted, + passphrase: 'wrong' + }, encryptedBuffer); + }); +})(); + +function test_rsa(padding) { + var input = new Buffer(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); + for (var i = 0; i < input.length; i++) + input[i] = (i * 7 + 11) & 0xff; + var bufferToEncrypt = new Buffer(input); + + padding = constants[padding]; + + var encryptedBuffer = crypto.publicEncrypt({ + key: rsaPubPem, + padding: padding + }, bufferToEncrypt); + + var decryptedBuffer = crypto.privateDecrypt({ + key: rsaKeyPem, + padding: padding + }, encryptedBuffer); + assert.equal(input, decryptedBuffer.toString()); +} + +test_rsa('RSA_NO_PADDING'); +test_rsa('RSA_PKCS1_PADDING'); +test_rsa('RSA_PKCS1_OAEP_PADDING'); + +// Test RSA key signing/verification +var rsaSign = crypto.createSign('RSA-SHA1'); +var rsaVerify = crypto.createVerify('RSA-SHA1'); +assert.ok(rsaSign); +assert.ok(rsaVerify); + +rsaSign.update(rsaPubPem); +var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); +assert.equal(rsaSignature, + '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); + +rsaVerify.update(rsaPubPem); +assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); + +// Test RSA key signing/verification with encrypted key +rsaSign = crypto.createSign('RSA-SHA1'); +rsaSign.update(rsaPubPem); +assert.doesNotThrow(function() { + var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; + rsaSignature = rsaSign.sign(signOptions, 'hex'); +}); +assert.equal(rsaSignature, + '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + + '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + + 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + + '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + + '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); + +rsaVerify = crypto.createVerify('RSA-SHA1'); +rsaVerify.update(rsaPubPem); +assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); + +rsaSign = crypto.createSign('RSA-SHA1'); +rsaSign.update(rsaPubPem); +assert.throws(function() { + var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; + rsaSign.sign(signOptions, 'hex'); +}); + +// +// Test RSA signing and verification +// +(function() { + var privateKey = fs.readFileSync( + common.fixturesDir + '/test_rsa_privkey_2.pem'); + + var publicKey = fs.readFileSync( + common.fixturesDir + '/test_rsa_pubkey_2.pem'); + + var input = 'I AM THE WALRUS'; + + var signature = + '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + + '0ddfb299bedeb1ad'; + + var sign = crypto.createSign('RSA-SHA256'); + sign.update(input); + + var output = sign.sign(privateKey, 'hex'); + assert.equal(output, signature); + + var verify = crypto.createVerify('RSA-SHA256'); + verify.update(input); + + assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); +})(); + + +// +// Test DSA signing and verification +// +(function() { + var input = 'I AM THE WALRUS'; + + // DSA signatures vary across runs so there is no static string to verify + // against + var sign = crypto.createSign('DSS1'); + sign.update(input); + var signature = sign.sign(dsaKeyPem, 'hex'); + + var verify = crypto.createVerify('DSS1'); + verify.update(input); + + assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); +})(); + + +// +// Test DSA signing and verification with encrypted key +// +(function() { + var input = 'I AM THE WALRUS'; + + var sign = crypto.createSign('DSS1'); + sign.update(input); + assert.throws(function() { + sign.sign({ key: dsaKeyPemEncrypted, passphrase: 'wrong' }, 'hex'); + }); + + // DSA signatures vary across runs so there is no static string to verify + // against + var sign = crypto.createSign('DSS1'); + sign.update(input); + + var signature; + assert.doesNotThrow(function() { + var signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; + signature = sign.sign(signOptions, 'hex'); + }); + + var verify = crypto.createVerify('DSS1'); + verify.update(input); + + assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); +})(); + + +// +// Test PBKDF2 with RFC 6070 test vectors (except #4) +// +function testPBKDF2(password, salt, iterations, keylen, expected) { + var actual = crypto.pbkdf2Sync(password, salt, iterations, keylen); + assert.equal(actual.toString('binary'), expected); + + crypto.pbkdf2(password, salt, iterations, keylen, function(err, actual) { + assert.equal(actual.toString('binary'), expected); + }); +} + + +testPBKDF2('password', 'salt', 1, 20, + '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + + '\xaf\x60\x12\x06\x2f\xe0\x37\xa6'); + +testPBKDF2('password', 'salt', 2, 20, + '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + + '\xce\x1d\x41\xf0\xd8\xde\x89\x57'); + +testPBKDF2('password', 'salt', 4096, 20, + '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + + '\xf7\x21\xd0\x65\xa4\x29\xc1'); + +testPBKDF2('passwordPASSWORDpassword', + 'saltSALTsaltSALTsaltSALTsaltSALTsalt', + 4096, + 25, + '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + + '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38'); + +testPBKDF2('pass\0word', 'sa\0lt', 4096, 16, + '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + + '\x25\xe0\xc3'); + +(function() { + var expected = + '64c486c55d30d4c5a079b8823b7d7cb37ff0556f537da8410233bcec330ed956'; + var key = crypto.pbkdf2Sync('password', 'salt', 32, 32, 'sha256'); + assert.equal(key.toString('hex'), expected); + + crypto.pbkdf2('password', 'salt', 32, 32, 'sha256', common.mustCall(ondone)); + function ondone(err, key) { + if (err) throw err; + assert.equal(key.toString('hex'), expected); + } +})(); + +function assertSorted(list) { + // Array#sort() modifies the list in place so make a copy. + var sorted = util._extend([], list).sort(); + assert.deepEqual(list, sorted); +} + +// Assume that we have at least AES-128-CBC. +assert.notEqual(0, crypto.getCiphers().length); +assert.notEqual(-1, crypto.getCiphers().indexOf('aes-128-cbc')); +assert.equal(-1, crypto.getCiphers().indexOf('AES-128-CBC')); +assertSorted(crypto.getCiphers()); + +// Assume that we have at least AES256-SHA. +var tls = require('tls'); +assert.notEqual(0, tls.getCiphers().length); +assert.notEqual(-1, tls.getCiphers().indexOf('aes256-sha')); +assert.equal(-1, tls.getCiphers().indexOf('AES256-SHA')); +assertSorted(tls.getCiphers()); + +// Assert that we have sha and sha1 but not SHA and SHA1. +assert.notEqual(0, crypto.getHashes().length); +assert.notEqual(-1, crypto.getHashes().indexOf('sha1')); +assert.notEqual(-1, crypto.getHashes().indexOf('sha')); +assert.equal(-1, crypto.getHashes().indexOf('SHA1')); +assert.equal(-1, crypto.getHashes().indexOf('SHA')); +assert.notEqual(-1, crypto.getHashes().indexOf('RSA-SHA1')); +assert.equal(-1, crypto.getHashes().indexOf('rsa-sha1')); +assertSorted(crypto.getHashes()); + +// Base64 padding regression test, see #4837. +(function() { + var c = crypto.createCipher('aes-256-cbc', 'secret'); + var s = c.update('test', 'utf8', 'base64') + c.final('base64'); + assert.equal(s, '375oxUQCIocvxmC5At+rvA=='); +})(); + +// Error path should not leak memory (check with valgrind). +assert.throws(function() { + crypto.pbkdf2('password', 'salt', 1, 20, null); +}); + +// Calling Cipher.final() or Decipher.final() twice should error but +// not assert. See #4886. +(function() { + var c = crypto.createCipher('aes-256-cbc', 'secret'); + try { c.final('xxx') } catch (e) { /* Ignore. */ } + try { c.final('xxx') } catch (e) { /* Ignore. */ } + try { c.final('xxx') } catch (e) { /* Ignore. */ } + var d = crypto.createDecipher('aes-256-cbc', 'secret'); + try { d.final('xxx') } catch (e) { /* Ignore. */ } + try { d.final('xxx') } catch (e) { /* Ignore. */ } + try { d.final('xxx') } catch (e) { /* Ignore. */ } +})(); + +// Regression test for #5482: string to Cipher#update() should not assert. +(function() { + var c = crypto.createCipher('aes192', '0123456789abcdef'); + c.update('update'); + c.final(); +})(); + +// #5655 regression tests, 'utf-8' and 'utf8' are identical. +(function() { + var c = crypto.createCipher('aes192', '0123456789abcdef'); + c.update('update', ''); // Defaults to "utf8". + c.final('utf-8'); // Should not throw. + + c = crypto.createCipher('aes192', '0123456789abcdef'); + c.update('update', 'utf8'); + c.final('utf-8'); // Should not throw. + + c = crypto.createCipher('aes192', '0123456789abcdef'); + c.update('update', 'utf-8'); + c.final('utf8'); // Should not throw. +})(); + +// Regression tests for #5725: hex input that's not a power of two should +// throw, not assert in C++ land. +assert.throws(function() { + crypto.createCipher('aes192', 'test').update('0', 'hex'); +}, /Bad input string/); + +assert.throws(function() { + crypto.createDecipher('aes192', 'test').update('0', 'hex'); +}, /Bad input string/); + +assert.throws(function() { + crypto.createHash('sha1').update('0', 'hex'); +}, /Bad input string/); + +assert.throws(function() { + crypto.createSign('RSA-SHA1').update('0', 'hex'); +}, /Bad input string/); + +assert.throws(function() { + crypto.createVerify('RSA-SHA1').update('0', 'hex'); +}, /Bad input string/); + +assert.throws(function() { + var private = [ + '-----BEGIN RSA PRIVATE KEY-----', + 'MIGrAgEAAiEA+3z+1QNF2/unumadiwEr+C5vfhezsb3hp4jAnCNRpPcCAwEAAQIgQNriSQK4', + 'EFwczDhMZp2dvbcz7OUUyt36z3S4usFPHSECEQD/41K7SujrstBfoCPzwC1xAhEA+5kt4BJy', + 'eKN7LggbF3Dk5wIQN6SL+fQ5H/+7NgARsVBp0QIRANxYRukavs4QvuyNhMx+vrkCEQCbf6j/', + 'Ig6/HueCK/0Jkmp+', + '-----END RSA PRIVATE KEY-----', + '' + ].join('\n'); + crypto.createSign('RSA-SHA256').update('test').sign(private); +}, /RSA_sign:digest too big for rsa key/); + +// Make sure memory isn't released before being returned +console.log(crypto.randomBytes(16)); + +// Test ECDH +var ecdh1 = crypto.createECDH('prime256v1'); +var ecdh2 = crypto.createECDH('prime256v1'); +var key1 = ecdh1.generateKeys(); +var key2 = ecdh2.generateKeys('hex'); +var secret1 = ecdh1.computeSecret(key2, 'hex', 'base64'); +var secret2 = ecdh2.computeSecret(key1, 'binary', 'buffer'); + +assert.equal(secret1, secret2.toString('base64')); + +// Point formats +assert.equal(ecdh1.getPublicKey('buffer', 'uncompressed')[0], 4); +var firstByte = ecdh1.getPublicKey('buffer', 'compressed')[0]; +assert(firstByte === 2 || firstByte === 3); +var firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0]; +assert(firstByte === 6 || firstByte === 7); + +// ECDH should check that point is on curve +var ecdh3 = crypto.createECDH('secp256k1'); +var key3 = ecdh3.generateKeys(); + +assert.throws(function() { + var secret3 = ecdh2.computeSecret(key3, 'binary', 'buffer'); +}); + +// ECDH should allow .setPrivateKey()/.setPublicKey() +var ecdh4 = crypto.createECDH('prime256v1'); + +ecdh4.setPrivateKey(ecdh1.getPrivateKey()); +ecdh4.setPublicKey(ecdh1.getPublicKey()); + +assert.throws(function() { + ecdh4.setPublicKey(ecdh3.getPublicKey()); +}); diff --git a/test/parallel/test-delayed-require.js b/test/parallel/test-delayed-require.js new file mode 100644 index 000000000..31c324976 --- /dev/null +++ b/test/parallel/test-delayed-require.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var a; +setTimeout(function() { + a = require('../fixtures/a'); +}, 50); + +process.on('exit', function() { + assert.equal(true, 'A' in a); + assert.equal('A', a.A()); + assert.equal('D', a.D()); +}); diff --git a/test/parallel/test-dgram-address.js b/test/parallel/test-dgram-address.js new file mode 100644 index 000000000..30d8eb0e1 --- /dev/null +++ b/test/parallel/test-dgram-address.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +// IPv4 Test +var localhost_ipv4 = '127.0.0.1'; +var socket_ipv4 = dgram.createSocket('udp4'); +var family_ipv4 = 'IPv4'; + +socket_ipv4.on('listening', function() { + var address_ipv4 = socket_ipv4.address(); + assert.strictEqual(address_ipv4.address, localhost_ipv4); + assert.strictEqual(address_ipv4.port, common.PORT); + assert.strictEqual(address_ipv4.family, family_ipv4); + socket_ipv4.close(); +}); + +socket_ipv4.on('error', function(e) { + console.log('Error on udp4 socket. ' + e.toString()); + socket_ipv4.close(); +}); + +socket_ipv4.bind(common.PORT, localhost_ipv4); + +// IPv6 Test +var localhost_ipv6 = '::1'; +var socket_ipv6 = dgram.createSocket('udp6'); +var family_ipv6 = 'IPv6'; + +socket_ipv6.on('listening', function() { + var address_ipv6 = socket_ipv6.address(); + assert.strictEqual(address_ipv6.address, localhost_ipv6); + assert.strictEqual(address_ipv6.port, common.PORT); + assert.strictEqual(address_ipv6.family, family_ipv6); + socket_ipv6.close(); +}); + +socket_ipv6.on('error', function(e) { + console.log('Error on udp6 socket. ' + e.toString()); + socket_ipv6.close(); +}); + +socket_ipv6.bind(common.PORT, localhost_ipv6); diff --git a/test/parallel/test-dgram-bind-default-address.js b/test/parallel/test-dgram-bind-default-address.js new file mode 100644 index 000000000..e7b65c57b --- /dev/null +++ b/test/parallel/test-dgram-bind-default-address.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +dgram.createSocket('udp4').bind(common.PORT + 0, common.mustCall(function() { + assert.equal(this.address().port, common.PORT + 0); + assert.equal(this.address().address, '0.0.0.0'); + this.close(); +})); + +if (!common.hasIPv6) { + console.error('Skipping udp6 part of test, no IPv6 support'); + return; +} + +dgram.createSocket('udp6').bind(common.PORT + 1, common.mustCall(function() { + assert.equal(this.address().port, common.PORT + 1); + var address = this.address().address; + if (address === '::ffff:0.0.0.0') + address = '::'; + assert.equal(address, '::'); + this.close(); +})); diff --git a/test/parallel/test-dgram-bind-shared-ports.js b/test/parallel/test-dgram-bind-shared-ports.js new file mode 100644 index 000000000..c9e22b592 --- /dev/null +++ b/test/parallel/test-dgram-bind-shared-ports.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var dgram = require('dgram'); + +// TODO XXX FIXME when windows supports clustered dgram ports re-enable this +// test +if (process.platform == 'win32') + process.exit(0); + +function noop() {} + +if (cluster.isMaster) { + var worker1 = cluster.fork(); + + worker1.on('message', function(msg) { + assert.equal(msg, 'success'); + var worker2 = cluster.fork(); + + worker2.on('message', function(msg) { + assert.equal(msg, 'socket2:EADDRINUSE'); + worker1.kill(); + worker2.kill(); + }); + }); +} else { + var socket1 = dgram.createSocket('udp4', noop); + var socket2 = dgram.createSocket('udp4', noop); + + socket1.on('error', function(err) { + // no errors expected + process.send('socket1:' + err.code); + }); + + socket2.on('error', function(err) { + // an error is expected on the second worker + process.send('socket2:' + err.code); + }); + + socket1.bind({ + address: 'localhost', + port: common.PORT, + exclusive: false + }, function() { + socket2.bind({port: common.PORT + 1, exclusive: true}, function() { + // the first worker should succeed + process.send('success'); + }); + }); +} diff --git a/test/parallel/test-dgram-bind.js b/test/parallel/test-dgram-bind.js new file mode 100644 index 000000000..8ee67637f --- /dev/null +++ b/test/parallel/test-dgram-bind.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var socket = dgram.createSocket('udp4'); + +socket.on('listening', function () { + socket.close(); +}); + +socket.bind(); // should not throw diff --git a/test/parallel/test-dgram-broadcast-multi-process.js b/test/parallel/test-dgram-broadcast-multi-process.js new file mode 100644 index 000000000..4d9eebc10 --- /dev/null +++ b/test/parallel/test-dgram-broadcast-multi-process.js @@ -0,0 +1,246 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + dgram = require('dgram'), + util = require('util'), + networkInterfaces = require('os').networkInterfaces(), + Buffer = require('buffer').Buffer, + fork = require('child_process').fork, + LOCAL_BROADCAST_HOST = '255.255.255.255', + TIMEOUT = 5000, + messages = [ + new Buffer('First message to send'), + new Buffer('Second message to send'), + new Buffer('Third message to send'), + new Buffer('Fourth message to send') + ]; + +// take the first non-internal interface as the address for binding +get_bindAddress: for (var name in networkInterfaces) { + var interfaces = networkInterfaces[name]; + for(var i = 0; i < interfaces.length; i++) { + var localInterface = interfaces[i]; + if (!localInterface.internal && localInterface.family === 'IPv4') { + var bindAddress = localInterface.address; + break get_bindAddress; + } + } +} +assert.ok(bindAddress); + +if (process.argv[2] !== 'child') { + var workers = {}, + listeners = 3, + listening = 0, + dead = 0, + i = 0, + done = 0, + timer = null; + + //exit the test if it doesn't succeed within TIMEOUT + timer = setTimeout(function() { + console.error('[PARENT] Responses were not received within %d ms.', + TIMEOUT); + console.error('[PARENT] Fail'); + + killChildren(workers); + + process.exit(1); + }, TIMEOUT); + + //launch child processes + for (var x = 0; x < listeners; x++) { + (function() { + var worker = fork(process.argv[1], ['child']); + workers[worker.pid] = worker; + + worker.messagesReceived = []; + + //handle the death of workers + worker.on('exit', function(code, signal) { + // don't consider this the true death if the worker + // has finished successfully + // or if the exit code is 0 + if (worker.isDone || code == 0) { + return; + } + + dead += 1; + console.error('[PARENT] Worker %d died. %d dead of %d', + worker.pid, + dead, + listeners); + + if (dead === listeners) { + console.error('[PARENT] All workers have died.'); + console.error('[PARENT] Fail'); + + killChildren(workers); + + process.exit(1); + } + }); + + worker.on('message', function(msg) { + if (msg.listening) { + listening += 1; + + if (listening === listeners) { + //all child process are listening, so start sending + sendSocket.sendNext(); + } + } + else if (msg.message) { + worker.messagesReceived.push(msg.message); + + if (worker.messagesReceived.length === messages.length) { + done += 1; + worker.isDone = true; + console.error('[PARENT] %d received %d messages total.', + worker.pid, + worker.messagesReceived.length); + } + + if (done === listeners) { + console.error('[PARENT] All workers have received the ' + + 'required number of ' + + 'messages. Will now compare.'); + + Object.keys(workers).forEach(function(pid) { + var worker = workers[pid]; + + var count = 0; + + worker.messagesReceived.forEach(function(buf) { + for (var i = 0; i < messages.length; ++i) { + if (buf.toString() === messages[i].toString()) { + count++; + break; + } + } + }); + + console.error('[PARENT] %d received %d matching messges.', + worker.pid, + count); + + assert.equal(count, messages.length, + 'A worker received an invalid multicast message'); + }); + + clearTimeout(timer); + console.error('[PARENT] Success'); + killChildren(workers); + } + } + }); + })(x); + } + + var sendSocket = dgram.createSocket({ + type: 'udp4', + reuseAddr: true + }); + + // bind the address explicitly for sending + // INADDR_BROADCAST to only one interface + sendSocket.bind(common.PORT, bindAddress); + sendSocket.on('listening', function () { + sendSocket.setBroadcast(true); + }); + + sendSocket.on('close', function() { + console.error('[PARENT] sendSocket closed'); + }); + + sendSocket.sendNext = function() { + var buf = messages[i++]; + + if (!buf) { + try { sendSocket.close(); } catch (e) {} + return; + } + + sendSocket.send(buf, 0, buf.length, + common.PORT, LOCAL_BROADCAST_HOST, function(err) { + + if (err) throw err; + + console.error('[PARENT] sent %s to %s:%s', + util.inspect(buf.toString()), + LOCAL_BROADCAST_HOST, common.PORT); + + process.nextTick(sendSocket.sendNext); + }); + }; + + function killChildren(children) { + Object.keys(children).forEach(function(key) { + var child = children[key]; + child.kill(); + }); + } +} + +if (process.argv[2] === 'child') { + var receivedMessages = []; + var listenSocket = dgram.createSocket({ + type: 'udp4', + reuseAddr: true + }); + + listenSocket.on('message', function(buf, rinfo) { + // receive udp messages only sent from parent + if (rinfo.address !== bindAddress) return; + + console.error('[CHILD] %s received %s from %j', + process.pid, + util.inspect(buf.toString()), + rinfo); + + receivedMessages.push(buf); + + process.send({ message: buf.toString() }); + + if (receivedMessages.length == messages.length) { + process.nextTick(function() { + listenSocket.close(); + }); + } + }); + + listenSocket.on('close', function() { + //HACK: Wait to exit the process to ensure that the parent + //process has had time to receive all messages via process.send() + //This may be indicitave of some other issue. + setTimeout(function() { + process.exit(); + }, 1000); + }); + + listenSocket.on('listening', function() { + process.send({ listening: true }); + }); + + listenSocket.bind(common.PORT); +} diff --git a/test/parallel/test-dgram-bytes-length.js b/test/parallel/test-dgram-bytes-length.js new file mode 100644 index 000000000..4e90f78c8 --- /dev/null +++ b/test/parallel/test-dgram-bytes-length.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var message = new Buffer('Some bytes'); +var client = dgram.createSocket('udp4'); +client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) { + assert.strictEqual(bytes, message.length); + client.close(); +}); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js new file mode 100644 index 000000000..77af6f13b --- /dev/null +++ b/test/parallel/test-dgram-close.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Ensure that if a dgram socket is closed before the DNS lookup completes, it +// won't crash. + +var assert = require('assert'), + common = require('../common'), + dgram = require('dgram'); + +var buf = new Buffer(1024); +buf.fill(42); + +var socket = dgram.createSocket('udp4'); +var handle = socket._handle; +socket.send(buf, 0, buf.length, common.PORT, 'localhost'); +socket.close(); +socket = null; + +// Verify that accessing handle after closure doesn't throw +setImmediate(function() { + setImmediate(function() { + console.log('Handle fd is: ', handle.fd); + }); +}); diff --git a/test/parallel/test-dgram-empty-packet.js b/test/parallel/test-dgram-empty-packet.js new file mode 100644 index 000000000..812e88a3b --- /dev/null +++ b/test/parallel/test-dgram-empty-packet.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var dgram = require('dgram'); +var callbacks = 0; +var client; +var timer; + +if (process.platform === 'darwin') { + console.error('Test is disabled due to 17894467 Apple bug'); + return; +} + +client = dgram.createSocket('udp4'); + +client.bind(common.PORT); + +function callback() { + callbacks++; + if (callbacks == 2) { + clearTimeout(timer); + client.close(); + } else if (callbacks > 2) { + throw new Error("the callbacks should be called only two times"); + } +} + +client.on('message', function (buffer, bytes) { + callback(); +}); + +client.send(new Buffer(1), 0, 0, common.PORT, "127.0.0.1", function (err, len) { + callback(); +}); + +timer = setTimeout(function() { + throw new Error('Timeout'); +}, 200); diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js new file mode 100644 index 000000000..6039629c4 --- /dev/null +++ b/test/parallel/test-dgram-implicit-bind.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var source = dgram.createSocket('udp4'); +var target = dgram.createSocket('udp4'); +var messages = 0; + +process.on('exit', function() { + assert.equal(messages, 2); +}); + +target.on('message', function(buf) { + if (buf.toString() === 'abc') ++messages; + if (buf.toString() === 'def') ++messages; + if (messages === 2) { + source.close(); + target.close(); + } +}); + +target.on('listening', function() { + // Second .send() call should not throw a bind error. + source.send(Buffer('abc'), 0, 3, common.PORT, '127.0.0.1'); + source.send(Buffer('def'), 0, 3, common.PORT, '127.0.0.1'); +}); + +target.bind(common.PORT); diff --git a/test/parallel/test-dgram-listen-after-bind.js b/test/parallel/test-dgram-listen-after-bind.js new file mode 100644 index 000000000..e5f1c4d65 --- /dev/null +++ b/test/parallel/test-dgram-listen-after-bind.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var socket = dgram.createSocket('udp4'); + +socket.bind(); + +var fired = false; +var timer = setTimeout(function () { + socket.close(); +}, 100); + +socket.on('listening', function () { + clearTimeout(timer); + fired = true; + socket.close(); +}); + +socket.on('close', function () { + assert(fired, 'listening should fire after bind'); +}); diff --git a/test/parallel/test-dgram-msgsize.js b/test/parallel/test-dgram-msgsize.js new file mode 100644 index 000000000..03f9cb532 --- /dev/null +++ b/test/parallel/test-dgram-msgsize.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +// Send a too big datagram. The destination doesn't matter because it's +// not supposed to get sent out anyway. +var buf = Buffer(256 * 1024); +var sock = dgram.createSocket('udp4'); +sock.send(buf, 0, buf.length, 12345, '127.0.0.1', common.mustCall(cb)); +function cb(err) { + assert(err instanceof Error); + assert.equal(err.code, 'EMSGSIZE'); + sock.close(); +} diff --git a/test/parallel/test-dgram-multicast-setTTL.js b/test/parallel/test-dgram-multicast-setTTL.js new file mode 100644 index 000000000..2ef0c167a --- /dev/null +++ b/test/parallel/test-dgram-multicast-setTTL.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + dgram = require('dgram'), + thrown = false, + socket = dgram.createSocket('udp4'); + +socket.bind(common.PORT); +socket.on('listening', function () { + socket.setMulticastTTL(16); + + //Try to set an invalid TTL (valid ttl is > 0 and < 256) + try { + socket.setMulticastTTL(1000); + } catch (e) { + thrown = true; + } + + assert(thrown, 'Setting an invalid multicast TTL should throw some error'); + + //close the socket + socket.close(); +}); diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js new file mode 100644 index 000000000..061c8417c --- /dev/null +++ b/test/parallel/test-dgram-oob-buffer.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Some operating systems report errors when an UDP message is sent to an +// unreachable host. This error can be reported by sendto() and even by +// recvfrom(). Node should not propagate this error to the user. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var socket = dgram.createSocket('udp4'); +var buf = Buffer([1,2,3,4]); + +function ok() {} +socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no +socket.send(buf, 0, 4, common.PORT, '127.0.0.1', ok); +socket.send(buf, 1, 3, common.PORT, '127.0.0.1', ok); +socket.send(buf, 3, 1, common.PORT, '127.0.0.1', ok); +// Since length of zero means nothing, don't error despite OOB. +socket.send(buf, 4, 0, common.PORT, '127.0.0.1', ok); + +assert.throws(function() { + socket.send(buf, 0, 5, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send(buf, 2, 3, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send(buf, 4, 4, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send('abc', 4, 1, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send('abc', 0, 4, common.PORT, '127.0.0.1', assert.fail); +}); +assert.throws(function() { + socket.send('abc', -1, 2, common.PORT, '127.0.0.1', assert.fail); +}); + +socket.close(); // FIXME should not be necessary diff --git a/test/parallel/test-dgram-pingpong.js b/test/parallel/test-dgram-pingpong.js new file mode 100644 index 000000000..992153293 --- /dev/null +++ b/test/parallel/test-dgram-pingpong.js @@ -0,0 +1,114 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var Buffer = require('buffer').Buffer; +var dgram = require('dgram'); + +var debug = false; +var tests_run = 0; + +function pingPongTest(port, host) { + var callbacks = 0; + var N = 500; + var count = 0; + var sent_final_ping = false; + + var server = dgram.createSocket('udp4', function(msg, rinfo) { + if (debug) console.log('server got: ' + msg + + ' from ' + rinfo.address + ':' + rinfo.port); + + if (/PING/.exec(msg)) { + var buf = new Buffer(4); + buf.write('PONG'); + server.send(buf, 0, buf.length, + rinfo.port, rinfo.address, + function(err, sent) { + callbacks++; + }); + } + }); + + server.on('error', function(e) { + throw e; + }); + + server.on('listening', function() { + console.log('server listening on ' + port + ' ' + host); + + var buf = new Buffer('PING'), + client = dgram.createSocket('udp4'); + + client.on('message', function(msg, rinfo) { + if (debug) console.log('client got: ' + msg + + ' from ' + rinfo.address + ':' + rinfo.port); + assert.equal('PONG', msg.toString('ascii')); + + count += 1; + + if (count < N) { + client.send(buf, 0, buf.length, port, 'localhost'); + } else { + sent_final_ping = true; + client.send(buf, 0, buf.length, port, 'localhost', function() { + client.close(); + }); + } + }); + + client.on('close', function() { + console.log('client has closed, closing server'); + assert.equal(N, count); + tests_run += 1; + server.close(); + assert.equal(N - 1, callbacks); + }); + + client.on('error', function(e) { + throw e; + }); + + console.log('Client sending to ' + port + ', localhost ' + buf); + client.send(buf, 0, buf.length, port, 'localhost', function(err, bytes) { + if (err) { + throw err; + } + console.log('Client sent ' + bytes + ' bytes'); + }); + count += 1; + }); + server.bind(port, host); +} + +// All are run at once, so run on different ports +pingPongTest(common.PORT + 0, 'localhost'); +pingPongTest(common.PORT + 1, 'localhost'); +pingPongTest(common.PORT + 2); +//pingPongTest('/tmp/pingpong.sock'); + +process.on('exit', function() { + assert.equal(3, tests_run); + console.log('done'); +}); diff --git a/test/parallel/test-dgram-ref.js b/test/parallel/test-dgram-ref.js new file mode 100644 index 000000000..ebbbac2fc --- /dev/null +++ b/test/parallel/test-dgram-ref.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var dgram = require('dgram'); + +// should not hang, see #1282 +dgram.createSocket('udp4'); +dgram.createSocket('udp6'); diff --git a/test/parallel/test-dgram-regress-4496.js b/test/parallel/test-dgram-regress-4496.js new file mode 100644 index 000000000..e45824a10 --- /dev/null +++ b/test/parallel/test-dgram-regress-4496.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Remove this test once we support sending strings. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +// Should throw but not crash. +var socket = dgram.createSocket('udp4'); +assert.throws(function() { socket.send(true, 0, 1, 1, 'host') }, TypeError); +assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host') }, TypeError); +socket.close(); diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js new file mode 100644 index 000000000..a9a12d458 --- /dev/null +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dgram = require('dgram'); + +var buf = Buffer('test'); +var host = '127.0.0.1'; +var sock = dgram.createSocket('udp4'); + +assert.throws(function() { + sock.send(); +}, TypeError); // First argument should be a buffer. + +assert.throws(function() { sock.send(buf, -1, 1, 1, host); }, RangeError); +assert.throws(function() { sock.send(buf, 1, -1, 1, host); }, RangeError); +assert.throws(function() { sock.send(buf, 1, 1, -1, host); }, RangeError); +assert.throws(function() { sock.send(buf, 5, 1, 1, host); }, RangeError); +assert.throws(function() { sock.send(buf, 1, 5, 1, host); }, RangeError); +assert.throws(function() { sock.send(buf, 1, 1, 0, host); }, RangeError); +assert.throws(function() { sock.send(buf, 1, 1, 65536, host); }, RangeError); diff --git a/test/parallel/test-dgram-send-callback-buffer-length.js b/test/parallel/test-dgram-send-callback-buffer-length.js new file mode 100644 index 000000000..c3b7d5ccc --- /dev/null +++ b/test/parallel/test-dgram-send-callback-buffer-length.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var dgram = require('dgram'); +var callbacks = 0; +var client, timer, buf, len, offset; + + +client = dgram.createSocket('udp4'); + +buf = new Buffer(256); +offset = 20; + +len = buf.length - offset; + + +client.send(buf, offset, len, common.PORT, "127.0.0.1", function (err, bytes) { + assert.notEqual(bytes, buf.length); + assert.equal(bytes, buf.length - offset); + clearTimeout(timer); + client.close(); +}); + +timer = setTimeout(function() { + throw new Error('Timeout'); +}, 200); diff --git a/test/parallel/test-dgram-send-empty-buffer.js b/test/parallel/test-dgram-send-empty-buffer.js new file mode 100644 index 000000000..4eb0ab4fc --- /dev/null +++ b/test/parallel/test-dgram-send-empty-buffer.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var dgram = require('dgram'); +var callbacks = 0; +var client, timer, buf; + +if (process.platform === 'darwin') { + console.error('Test is disabled due to 17894467 Apple bug'); + return; +} + + +client = dgram.createSocket('udp4'); + +client.bind(common.PORT); + +client.on('message', function (buffer, bytes) { + clearTimeout(timer); + client.close(); +}); + +buf = new Buffer(0); +client.send(buf, 0, 0, common.PORT, "127.0.0.1", function (err, len) { }); + +timer = setTimeout(function() { + throw new Error('Timeout'); +}, 200); diff --git a/test/parallel/test-dgram-udp4.js b/test/parallel/test-dgram-udp4.js new file mode 100644 index 000000000..cc1f1c088 --- /dev/null +++ b/test/parallel/test-dgram-udp4.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'), + dgram = require('dgram'), server, client, + server_port = common.PORT, + message_to_send = 'A message to send', + timer; + +server = dgram.createSocket('udp4'); +server.on('message', function(msg, rinfo) { + console.log('server got: ' + msg + + ' from ' + rinfo.address + ':' + rinfo.port); + assert.strictEqual(rinfo.address, '127.0.0.1'); + assert.strictEqual(msg.toString(), message_to_send.toString()); + server.send(msg, 0, msg.length, rinfo.port, rinfo.address); +}); +server.on('listening', function() { + var address = server.address(); + console.log('server is listening on ' + address.address + ':' + address.port); + client = dgram.createSocket('udp4'); + client.on('message', function(msg, rinfo) { + console.log('client got: ' + msg + + ' from ' + rinfo.address + ':' + address.port); + assert.strictEqual(rinfo.address, '127.0.0.1'); + assert.strictEqual(rinfo.port, server_port); + assert.strictEqual(msg.toString(), message_to_send.toString()); + client.close(); + server.close(); + }); + client.send(message_to_send, 0, message_to_send.length, + server_port, 'localhost', function(err) { + if (err) { + console.log('Caught error in client send.'); + throw err; + } + }); + client.on('close', + function() { + if (server.fd === null) { + clearTimeout(timer); + } + }); +}); +server.on('close', function() { + if (client.fd === null) { + clearTimeout(timer); + } +}); +server.bind(server_port); + +timer = setTimeout(function() { + throw new Error('Timeout'); +}, 200); diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js new file mode 100644 index 000000000..38abbac27 --- /dev/null +++ b/test/parallel/test-dgram-unref.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var dgram = require('dgram'); +var closed = false; + +var s = dgram.createSocket('udp4'); +s.bind(); +s.unref(); + +setTimeout(function() { + closed = true; + s.close(); +}, 1000).unref(); + +process.on('exit', function() { + assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); +}); diff --git a/test/parallel/test-dh-padding.js b/test/parallel/test-dh-padding.js new file mode 100644 index 000000000..753c0eb81 --- /dev/null +++ b/test/parallel/test-dh-padding.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +var prime = 'c51f7bf8f0e1cf899243cdf408b1bc7c09c010e33ef7f3fbe5bd5feaf906113b'; +var apub = '6fe9f37037d8d017f908378c1ee04fe60e1cd3668bfc5075fac55c2f7153dd84'; +var bpub = '31d83e167fdf956c9dae6b980140577a9f8868acbfcbdc19113e58bfb9223abc'; +var apriv = '4fbfd4661f9181bbf574537b1a78adf473e8e771eef13c605e963c0f3094b697'; +var secret = '25616eed33f1af7975bbd0a8071d98a014f538b243bef90d76c08e81a0b3c500'; + +var p = crypto.createDiffieHellman(prime, 'hex'); + +p.setPublicKey(apub, 'hex'); +p.setPrivateKey(apriv, 'hex'); + +assert.equal( + p.computeSecret(bpub, 'hex', 'hex'), + '0025616eed33f1af7975bbd0a8071d98a014f538b243bef90d76c08e81a0b3c5' +); diff --git a/test/parallel/test-dns-cares-domains.js b/test/parallel/test-dns-cares-domains.js new file mode 100644 index 000000000..8581ed64d --- /dev/null +++ b/test/parallel/test-dns-cares-domains.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dns = require('dns'); +var domain = require('domain'); + +var methods = [ + 'resolve4', + 'resolve6', + 'resolveCname', + 'resolveMx', + 'resolveNs', + 'resolveTxt', + 'resolveSrv', + 'resolveNaptr', + 'resolveSoa' +] + +methods.forEach(function(method) { + var d = domain.create(); + d.run(function() { + dns[method]('google.com', function() { + assert.strictEqual(process.domain, d, method + ' retains domain') + }); + }); +}); diff --git a/test/parallel/test-dns-lookup-cb-error.js b/test/parallel/test-dns-lookup-cb-error.js new file mode 100644 index 000000000..036581098 --- /dev/null +++ b/test/parallel/test-dns-lookup-cb-error.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cares = process.binding('cares_wrap'); + +var dns = require('dns'); + +// Stub `getaddrinfo` to *always* error. +cares.getaddrinfo = function() { + return process.binding('uv').UV_ENOENT; +}; + +assert.doesNotThrow(function() { + var tickValue = 0; + + dns.lookup('example.com', function(error, result, addressType) { + assert.equal(tickValue, 1); + assert.equal(error.code, 'ENOENT'); + }); + + // Make sure that the error callback is called + // on next tick. + tickValue = 1; +}); diff --git a/test/parallel/test-dns-regress-6244.js b/test/parallel/test-dns-regress-6244.js new file mode 100644 index 000000000..ca2957926 --- /dev/null +++ b/test/parallel/test-dns-regress-6244.js @@ -0,0 +1,26 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var dns = require('dns'); + +// Should not segfault, see #6244. +dns.resolve4('127.0.0.1', common.mustCall(function() { })); diff --git a/test/parallel/test-dns-regress-7070.js b/test/parallel/test-dns-regress-7070.js new file mode 100644 index 000000000..9aca4f728 --- /dev/null +++ b/test/parallel/test-dns-regress-7070.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var dns = require('dns'); + +// Should not raise assertion error. Issue #7070 +assert.throws(function () { dns.resolveNs([]); }); // bad name +assert.throws(function () { dns.resolveNs(''); }); // bad callback diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js new file mode 100644 index 000000000..405bcf0a0 --- /dev/null +++ b/test/parallel/test-dns.js @@ -0,0 +1,167 @@ +// Copyright Joyent, Inc. and other Node contributors. + +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: + +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var dns = require('dns'); + +var existing = dns.getServers(); +assert(existing.length); + +function noop() {} + +var goog = [ + '8.8.8.8', + '8.8.4.4', +]; +assert.doesNotThrow(function () { dns.setServers(goog) }); +assert.deepEqual(dns.getServers(), goog); +assert.throws(function () { dns.setServers(['foobar']) }); +assert.deepEqual(dns.getServers(), goog); + +var goog6 = [ + '2001:4860:4860::8888', + '2001:4860:4860::8844', +]; +assert.doesNotThrow(function () { dns.setServers(goog6) }); +assert.deepEqual(dns.getServers(), goog6); + +goog6.push('4.4.4.4'); +dns.setServers(goog6); +assert.deepEqual(dns.getServers(), goog6); + +var ports = [ + '4.4.4.4:53', + '[2001:4860:4860::8888]:53', +]; +var portsExpected = [ + '4.4.4.4', + '2001:4860:4860::8888', +]; +dns.setServers(ports); +assert.deepEqual(dns.getServers(), portsExpected); + +assert.doesNotThrow(function () { dns.setServers([]); }); +assert.deepEqual(dns.getServers(), []); + +assert.throws(function() { + dns.resolve('test.com', [], noop); +}, function(err) { + return !(err instanceof TypeError); +}, 'Unexpected error'); + +// dns.lookup should accept falsey and string values +assert.throws(function() { + dns.lookup({}, noop); +}, 'invalid arguments: hostname must be a string or falsey'); + +assert.throws(function() { + dns.lookup([], noop); +}, 'invalid arguments: hostname must be a string or falsey'); + +assert.throws(function() { + dns.lookup(true, noop); +}, 'invalid arguments: hostname must be a string or falsey'); + +assert.throws(function() { + dns.lookup(1, noop); +}, 'invalid arguments: hostname must be a string or falsey'); + +assert.throws(function() { + dns.lookup(noop, noop); +}, 'invalid arguments: hostname must be a string or falsey'); + +assert.doesNotThrow(function() { + dns.lookup('', noop); +}); + +assert.doesNotThrow(function() { + dns.lookup(null, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup(undefined, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup(0, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup(NaN, noop); +}); + +/* + * Make sure that dns.lookup throws if hints does not represent a valid flag. + * (dns.V4MAPPED | dns.ADDRCONFIG) + 1 is invalid because: + * - it's different from dns.V4MAPPED and dns.ADDRCONFIG. + * - it's different from them bitwise ored. + * - it's different from 0. + * - it's an odd number different than 1, and thus is invalid, because + * flags are either === 1 or even. + */ +assert.throws(function() { + dns.lookup('www.google.com', { hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1 }, + noop); +}); + +assert.throws(function() { + dns.lookup('www.google.com'); +}, 'invalid arguments: callback must be passed'); + +assert.throws(function() { + dns.lookup('www.google.com', 4); +}, 'invalid arguments: callback must be passed'); + +assert.doesNotThrow(function() { + dns.lookup('www.google.com', 6, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup('www.google.com', {}, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup('www.google.com', { + family: 4, + hints: 0 + }, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup('www.google.com', { + family: 6, + hints: dns.ADDRCONFIG + }, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup('www.google.com', { + hints: dns.V4MAPPED + }, noop); +}); + +assert.doesNotThrow(function() { + dns.lookup('www.google.com', { + hints: dns.ADDRCONFIG | dns.V4MAPPED + }, noop); +}); diff --git a/test/parallel/test-domain-crypto.js b/test/parallel/test-domain-crypto.js new file mode 100644 index 000000000..66e962880 --- /dev/null +++ b/test/parallel/test-domain-crypto.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +try { + var crypto = require('crypto'); +} catch (e) { + console.log('Not compiled with OPENSSL support.'); + process.exit(); +} + +// the missing var keyword is intentional +domain = require('domain'); + +// should not throw a 'TypeError: undefined is not a function' exception +crypto.randomBytes(8); +crypto.randomBytes(8, function() {}); +crypto.pseudoRandomBytes(8); +crypto.pseudoRandomBytes(8, function() {}); +crypto.pbkdf2('password', 'salt', 8, 8, function() {}); diff --git a/test/parallel/test-domain-enter-exit.js b/test/parallel/test-domain-enter-exit.js new file mode 100644 index 000000000..7d248ea15 --- /dev/null +++ b/test/parallel/test-domain-enter-exit.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Make sure the domain stack is a stack + +var assert = require('assert'); +var domain = require('domain'); + +function names(array) { + return array.map(function(d) { + return d.name + }).join(', '); +} + +var a = domain.create(); +a.name = 'a'; +var b = domain.create(); +b.name = 'b'; +var c = domain.create(); +c.name = 'c'; + +a.enter(); // push +assert.deepEqual(domain._stack, [a], + 'a not pushed: ' + names(domain._stack)); + +b.enter(); // push +assert.deepEqual(domain._stack, [a, b], + 'b not pushed: ' + names(domain._stack)); + +c.enter(); // push +assert.deepEqual(domain._stack, [a, b, c], + 'c not pushed: ' + names(domain._stack)); + +b.exit(); // pop +assert.deepEqual(domain._stack, [a], + 'b and c not popped: ' + names(domain._stack)); + +b.enter(); // push +assert.deepEqual(domain._stack, [a, b], + 'b not pushed: ' + names(domain._stack)); diff --git a/test/parallel/test-domain-exit-dispose-again.js b/test/parallel/test-domain-exit-dispose-again.js new file mode 100644 index 000000000..22928f260 --- /dev/null +++ b/test/parallel/test-domain-exit-dispose-again.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var domain = require('domain'); +var disposalFailed = false; + +// no matter what happens, we should increment a 10 times. +var a = 0; +log(); +function log(){ + console.log(a++, process.domain); + if (a < 10) setTimeout(log, 20); +} + +var secondTimerRan = false; + +// in 50ms we'll throw an error. +setTimeout(err, 50); +setTimeout(secondTimer, 50); +function err(){ + var d = domain.create(); + d.on('error', handle); + d.run(err2); + + function err2() { + // this timeout should never be called, since the domain gets + // disposed when the error happens. + setTimeout(function() { + console.error('This should not happen.'); + disposalFailed = true; + process.exit(1); + }); + + // this function doesn't exist, and throws an error as a result. + err3(); + } + + function handle(e) { + // this should clean up everything properly. + d.dispose(); + console.error(e); + console.error('in handler', process.domain, process.domain === d); + } +} + +function secondTimer() { + console.log('In second timer'); + secondTimerRan = true; +} + +process.on('exit', function() { + assert.equal(a, 10); + assert.equal(disposalFailed, false); + assert(secondTimerRan); + console.log('ok'); +}); diff --git a/test/parallel/test-domain-exit-dispose.js b/test/parallel/test-domain-exit-dispose.js new file mode 100644 index 000000000..fd990911c --- /dev/null +++ b/test/parallel/test-domain-exit-dispose.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var domain = require('domain'); +var disposalFailed = false; + +// no matter what happens, we should increment a 10 times. +var a = 0; +log(); +function log(){ + console.log(a++, process.domain); + if (a < 10) setTimeout(log, 20); +} + +// in 50ms we'll throw an error. +setTimeout(err, 50); +function err(){ + var d = domain.create(); + d.on('error', handle); + d.run(err2); + + function err2() { + // this timeout should never be called, since the domain gets + // disposed when the error happens. + setTimeout(function() { + console.error('This should not happen.'); + disposalFailed = true; + process.exit(1); + }); + + // this function doesn't exist, and throws an error as a result. + err3(); + } + + function handle(e) { + // this should clean up everything properly. + d.dispose(); + console.error(e); + console.error('in handler', process.domain, process.domain === d); + } +} + +process.on('exit', function() { + assert.equal(a, 10); + assert.equal(disposalFailed, false); + console.log('ok'); +}); diff --git a/test/parallel/test-domain-from-timer.js b/test/parallel/test-domain-from-timer.js new file mode 100644 index 000000000..3e73a5c4b --- /dev/null +++ b/test/parallel/test-domain-from-timer.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Simple tests of most basic domain functionality. + +var common = require('../common'); +var assert = require('assert'); + +// timeouts call the callback directly from cc, so need to make sure the +// domain will be used regardless +setTimeout(function() { + var domain = require('domain'); + var d = domain.create(); + d.run(function() { + process.nextTick(function() { + console.trace('in nexttick', process.domain === d) + assert.equal(process.domain, d); + }); + }); +}); diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js new file mode 100644 index 000000000..57e8ac4d1 --- /dev/null +++ b/test/parallel/test-domain-http-server.js @@ -0,0 +1,114 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var domain = require('domain'); +var http = require('http'); +var assert = require('assert'); +var common = require('../common.js'); + +var objects = { foo: 'bar', baz: {}, num: 42, arr: [1,2,3] }; +objects.baz.asdf = objects; + +var serverCaught = 0; +var clientCaught = 0; +var disposeEmit = 0; + +var server = http.createServer(function(req, res) { + var dom = domain.create(); + req.resume(); + dom.add(req); + dom.add(res); + + dom.on('error', function(er) { + serverCaught++; + console.log('horray! got a server error', er); + // try to send a 500. If that fails, oh well. + res.writeHead(500, {'content-type':'text/plain'}); + res.end(er.stack || er.message || 'Unknown error'); + }); + + dom.run(function() { + // Now, an action that has the potential to fail! + // if you request 'baz', then it'll throw a JSON circular ref error. + var data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); + + // this line will throw if you pick an unknown key + assert(data !== undefined, 'Data should not be undefined'); + + res.writeHead(200); + res.end(data); + }); +}); + +server.listen(common.PORT, next); + +function next() { + console.log('listening on localhost:%d', common.PORT); + + var requests = 0; + var responses = 0; + + makeReq('/'); + makeReq('/foo'); + makeReq('/arr'); + makeReq('/baz'); + makeReq('/num'); + + function makeReq(p) { + requests++; + + var dom = domain.create(); + dom.on('error', function(er) { + clientCaught++; + console.log('client error', er); + req.socket.destroy(); + }); + + var req = http.get({ host: 'localhost', port: common.PORT, path: p }); + dom.add(req); + req.on('response', function(res) { + responses++; + console.error('requests=%d responses=%d', requests, responses); + if (responses === requests) { + console.error('done, closing server'); + // no more coming. + server.close(); + } + + dom.add(res); + var d = ''; + res.on('data', function(c) { + d += c; + }); + res.on('end', function() { + console.error('trying to parse json', d); + d = JSON.parse(d); + console.log('json!', d); + }); + }); + } +} + +process.on('exit', function() { + assert.equal(serverCaught, 2); + assert.equal(clientCaught, 2); + console.log('ok'); +}); diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js new file mode 100644 index 000000000..c701c9315 --- /dev/null +++ b/test/parallel/test-domain-implicit-fs.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Simple tests of most basic domain functionality. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); +var caught = 0; +var expectCaught = 1; + +var d = new domain.Domain(); +var e = new events.EventEmitter(); + +d.on('error', function(er) { + console.error('caught', er); + + assert.strictEqual(er.domain, d); + assert.strictEqual(er.domainThrown, true); + assert.ok(!er.domainEmitter); + assert.strictEqual(er.code, 'ENOENT'); + assert.ok(/\bthis file does not exist\b/i.test(er.path)); + assert.strictEqual(typeof er.errno, 'number'); + + caught++; +}); + +process.on('exit', function() { + console.error('exit'); + assert.equal(caught, expectCaught); + console.log('ok'); +}); + + +// implicit handling of thrown errors while in a domain, via the +// single entry points of ReqWrap and MakeCallback. Even if +// we try very hard to escape, there should be no way to, even if +// we go many levels deep through timeouts and multiple IO calls. +// Everything that happens between the domain.enter() and domain.exit() +// calls will be bound to the domain, even if multiple levels of +// handles are created. +d.run(function() { + setTimeout(function() { + var fs = require('fs'); + fs.readdir(__dirname, function() { + fs.open('this file does not exist', 'r', function(er) { + if (er) throw er; + throw new Error('should not get here!'); + }); + }); + }, 100); +}); diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js new file mode 100644 index 000000000..68e4b11a6 --- /dev/null +++ b/test/parallel/test-domain-multi.js @@ -0,0 +1,99 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Tests of multiple domains happening at once. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); + +var caughtA = false; +var caughtB = false; +var caughtC = false; + + +var a = domain.create(); +a.enter(); // this will be our "root" domain +a.on('error', function(er) { + caughtA = true; + console.log('This should not happen'); + throw er; +}); + + +var http = require('http'); +var server = http.createServer(function (req, res) { + // child domain of a. + var b = domain.create(); + a.add(b); + + // treat these EE objects as if they are a part of the b domain + // so, an 'error' event on them propagates to the domain, rather + // than being thrown. + b.add(req); + b.add(res); + + b.on('error', function (er) { + caughtB = true; + console.error('Error encountered', er) + if (res) { + res.writeHead(500); + res.end('An error occurred'); + } + // res.writeHead(500), res.destroy, etc. + server.close(); + }); + + // XXX this bind should not be necessary. + // the write cb behavior in http/net should use an + // event so that it picks up the domain handling. + res.write('HELLO\n', b.bind(function() { + throw new Error('this kills domain B, not A'); + })); + +}).listen(common.PORT); + +var c = domain.create(); +var req = http.get({ host: 'localhost', port: common.PORT }) + +// add the request to the C domain +c.add(req); + +req.on('response', function(res) { + console.error('got response'); + // add the response object to the C domain + c.add(res); + res.pipe(process.stdout); +}); + +c.on('error', function(er) { + caughtC = true; + console.error('Error on c', er.message); +}); + +process.on('exit', function() { + assert.equal(caughtA, false); + assert.equal(caughtB, true) + assert.equal(caughtC, true) + console.log('ok - Errors went where they were supposed to go'); +}); diff --git a/test/parallel/test-domain-nested-throw.js b/test/parallel/test-domain-nested-throw.js new file mode 100644 index 000000000..e11948667 --- /dev/null +++ b/test/parallel/test-domain-nested-throw.js @@ -0,0 +1,113 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var domain = require('domain'); + +var dispose; +switch (process.argv[2]) { + case 'true': + dispose = true; + break; + case 'false': + dispose = false; + break; + default: + parent(); + return; +} + +function parent() { + var node = process.execPath; + var spawn = require('child_process').spawn; + var opt = { stdio: 'inherit' }; + var child = spawn(node, [__filename, 'true'], opt); + child.on('exit', function(c) { + assert(!c); + child = spawn(node, [__filename, 'false'], opt); + child.on('exit', function(c) { + assert(!c); + console.log('ok'); + }); + }); +} + +var gotDomain1Error = false; +var gotDomain2Error = false; + +var threw1 = false; +var threw2 = false; + +function throw1() { + threw1 = true; + throw new Error('handled by domain1'); +} + +function throw2() { + threw2 = true; + throw new Error('handled by domain2'); +} + +function inner(throw1, throw2) { + var domain1 = domain.createDomain(); + + domain1.on('error', function (err) { + if (gotDomain1Error) { + console.error('got domain 1 twice'); + process.exit(1); + } + if (dispose) domain1.dispose(); + gotDomain1Error = true; + throw2(); + }); + + domain1.run(function () { + throw1(); + }); +} + +function outer() { + var domain2 = domain.createDomain(); + + domain2.on('error', function (err) { + if (gotDomain2Error) { + console.error('got domain 2 twice'); + process.exit(1); + } + gotDomain2Error = true; + }); + + domain2.run(function () { + inner(throw1, throw2); + }); +} + +process.on('exit', function() { + assert(gotDomain1Error); + assert(gotDomain2Error); + assert(threw1); + assert(threw2); + console.log('ok', dispose); +}); + +outer(); diff --git a/test/parallel/test-domain-nested.js b/test/parallel/test-domain-nested.js new file mode 100644 index 000000000..efd672b25 --- /dev/null +++ b/test/parallel/test-domain-nested.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Make sure that the nested domains don't cause the domain stack to grow + +var assert = require('assert'); +var domain = require('domain'); + +process.on('exit', function(c) { + assert.equal(domain._stack.length, 0); +}); + +domain.create().run(function() { + domain.create().run(function() { + domain.create().run(function() { + domain.create().on("error", function(e) { + // Don't need to do anything here + }).run(function() { + throw new Error("died") + }) + }) + }) +}) diff --git a/test/parallel/test-domain-safe-exit.js b/test/parallel/test-domain-safe-exit.js new file mode 100644 index 000000000..a7dcef078 --- /dev/null +++ b/test/parallel/test-domain-safe-exit.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Make sure the domain stack doesn't get clobbered by un-matched .exit() + +var assert = require('assert'); +var domain = require('domain'); + +var a = domain.create(); +var b = domain.create(); + +a.enter(); // push +b.enter(); // push +assert.deepEqual(domain._stack, [a, b], 'b not pushed'); + +domain.create().exit(); // no-op +assert.deepEqual(domain._stack, [a, b], 'stack mangled!'); diff --git a/test/parallel/test-domain-stack.js b/test/parallel/test-domain-stack.js new file mode 100644 index 000000000..eecb85b4b --- /dev/null +++ b/test/parallel/test-domain-stack.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Make sure that the domain stack doesn't get out of hand. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); + +var a = domain.create(); +a.name = 'a'; + +a.on('error', function() { + if (domain._stack.length > 5) { + console.error('leaking!', domain._stack); + process.exit(1); + } +}); + +var foo = a.bind(function() { + throw new Error('error from foo'); +}); + +for (var i = 0; i < 1000; i++) { + process.nextTick(foo); +} + +process.on('exit', function(c) { + if (!c) console.log('ok'); +}); diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js new file mode 100644 index 000000000..388673c08 --- /dev/null +++ b/test/parallel/test-domain-timers.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var domain = require('domain'); +var assert = require('assert'); +var common = require('../common.js'); + +var timeout_err, timeout, immediate_err; + +var timeoutd = domain.create(); + +timeoutd.on('error', function(e) { + timeout_err = e; + clearTimeout(timeout); +}); + +timeoutd.run(function() { + setTimeout(function() { + throw new Error('Timeout UNREFd'); + }).unref(); +}); + +var immediated = domain.create(); + +immediated.on('error', function(e) { + immediate_err = e; +}); + +immediated.run(function() { + setImmediate(function() { + throw new Error('Immediate Error'); + }); +}); + +timeout = setTimeout(function() {}, 10 * 1000); + +process.on('exit', function() { + assert.equal(timeout_err.message, 'Timeout UNREFd', + 'Domain should catch timer error'); + assert.equal(immediate_err.message, 'Immediate Error', + 'Domain should catch immediate error'); +}); diff --git a/test/parallel/test-domain.js b/test/parallel/test-domain.js new file mode 100644 index 000000000..41eb602e4 --- /dev/null +++ b/test/parallel/test-domain.js @@ -0,0 +1,285 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// Simple tests of most basic domain functionality. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); +var events = require('events'); +var fs = require('fs'); +var caught = 0; +var expectCaught = 0; + +var d = new domain.Domain(); +var e = new events.EventEmitter(); + +d.on('error', function(er) { + console.error('caught', er && (er.message || er)); + + var er_message = er.message; + var er_path = er.path + + // On windows, error messages can contain full path names. If this is the + // case, remove the directory part. + if (typeof er_path === 'string') { + var slash = er_path.lastIndexOf('\\'); + if (slash !== -1) { + var dir = er_path.slice(0, slash + 1); + er_path = er_path.replace(dir, ''); + er_message = er_message.replace(dir, ''); + } + } + + switch (er_message) { + case 'emitted': + assert.equal(er.domain, d); + assert.equal(er.domainEmitter, e); + assert.equal(er.domainThrown, false); + break; + + case 'bound': + assert.ok(!er.domainEmitter); + assert.equal(er.domain, d); + assert.equal(er.domainBound, fn); + assert.equal(er.domainThrown, false); + break; + + case 'thrown': + assert.ok(!er.domainEmitter); + assert.equal(er.domain, d); + assert.equal(er.domainThrown, true); + break; + + case "ENOENT, open 'this file does not exist'": + assert.equal(er.domain, d); + assert.equal(er.domainThrown, false); + assert.equal(typeof er.domainBound, 'function'); + assert.ok(!er.domainEmitter); + assert.equal(er.code, 'ENOENT'); + assert.equal(er_path, 'this file does not exist'); + assert.equal(typeof er.errno, 'number'); + break; + + case "ENOENT, open 'stream for nonexistent file'": + assert.equal(typeof er.errno, 'number'); + assert.equal(er.code, 'ENOENT'); + assert.equal(er_path, 'stream for nonexistent file'); + assert.equal(er.domain, d); + assert.equal(er.domainEmitter, fst); + assert.ok(!er.domainBound); + assert.equal(er.domainThrown, false); + break; + + case 'implicit': + assert.equal(er.domainEmitter, implicit); + assert.equal(er.domain, d); + assert.equal(er.domainThrown, false); + assert.ok(!er.domainBound); + break; + + case 'implicit timer': + assert.equal(er.domain, d); + assert.equal(er.domainThrown, true); + assert.ok(!er.domainEmitter); + assert.ok(!er.domainBound); + break; + + case 'Cannot read property \'isDirectory\' of undefined': + assert.equal(er.domain, d); + assert.ok(!er.domainEmitter); + assert.ok(!er.domainBound); + break; + + case 'nextTick execution loop': + assert.equal(er.domain, d); + assert.ok(!er.domainEmitter); + assert.ok(!er.domainBound); + break; + + default: + console.error('unexpected error, throwing %j', er.message, er); + throw er; + } + + caught++; +}); + + + +process.on('exit', function() { + console.error('exit', caught, expectCaught); + assert.equal(caught, expectCaught, 'caught the expected number of errors'); + console.log('ok'); +}); + + + +// revert to using the domain when a callback is passed to nextTick in +// the middle of a tickCallback loop +d.run(function() { + process.nextTick(function() { + throw new Error('nextTick execution loop'); + }); +}); +expectCaught++; + + + +// catch thrown errors no matter how many times we enter the event loop +// this only uses implicit binding, except for the first function +// passed to d.run(). The rest are implicitly bound by virtue of being +// set up while in the scope of the d domain. +d.run(function() { + process.nextTick(function() { + var i = setInterval(function () { + clearInterval(i); + setTimeout(function() { + fs.stat('this file does not exist', function(er, stat) { + // uh oh! stat isn't set! + // pretty common error. + console.log(stat.isDirectory()); + }); + }); + }); + }); +}); +expectCaught++; + + + +// implicit addition of a timer created within a domain-bound context. +d.run(function() { + setTimeout(function() { + throw new Error('implicit timer'); + }); +}); +expectCaught++; + + + +// Event emitters added to the domain have their errors routed. +d.add(e); +e.emit('error', new Error('emitted')); +expectCaught++; + + + +// get rid of the `if (er) return cb(er)` malarky, by intercepting +// the cb functions to the domain, and using the intercepted function +// as a callback instead. +function fn(er) { + throw new Error('This function should never be called!'); + process.exit(1); +} + +var bound = d.intercept(fn); +bound(new Error('bound')); +expectCaught++; + + + +// intercepted should never pass first argument to callback +function fn2(data) { + assert.equal(data, 'data', 'should not be null err argument') +} + +var bound = d.intercept(fn2); +bound(null, 'data'); + +// intercepted should never pass first argument to callback +// even if arguments length is more than 2. +function fn3(data, data2) { + assert.equal(data, 'data', 'should not be null err argument'); + assert.equal(data2, 'data2', 'should not be data argument'); +} + +bound = d.intercept(fn3); +bound(null, 'data', 'data2'); + +// throwing in a bound fn is also caught, +// even if it's asynchronous, by hitting the +// global uncaughtException handler. This doesn't +// require interception, since throws are always +// caught by the domain. +function thrower() { + throw new Error('thrown'); +} +setTimeout(d.bind(thrower), 100); +expectCaught++; + + + +// Pass an intercepted function to an fs operation that fails. +fs.open('this file does not exist', 'r', d.intercept(function(er) { + console.error('should not get here!', er); + throw new Error('should not get here!'); +}, true)); +expectCaught++; + + + +// implicit addition by being created within a domain-bound context. +var implicit; + +d.run(function() { + implicit = new events.EventEmitter; +}); + +setTimeout(function() { + // escape from the domain, but implicit is still bound to it. + implicit.emit('error', new Error('implicit')); +}, 10); +expectCaught++; + + +var result = d.run(function () { + return 'return value'; +}); +assert.equal(result, 'return value'); + + +// check if the executed function take in count the applied parameters +result = d.run(function (a, b) { + return a + ' ' + b; +}, 'return', 'value'); +assert.equal(result, 'return value'); + + +var fst = fs.createReadStream('stream for nonexistent file') +d.add(fst) +expectCaught++; + +[42, null, , false, function(){}, 'string'].forEach(function(something) { + var d = new domain.Domain(); + d.run(function() { + process.nextTick(function() { + throw something; + }); + expectCaught++; + }); + + d.on('error', function(er) { + assert.strictEqual(something, er); + caught++; + }); +}); diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js new file mode 100644 index 000000000..c187998dd --- /dev/null +++ b/test/parallel/test-error-reporting.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var path = require('path'); + +var exits = 0; + +function errExec(script, callback) { + var cmd = '"' + process.argv[0] + '" "' + + path.join(common.fixturesDir, script) + '"'; + return exec(cmd, function(err, stdout, stderr) { + // There was some error + assert.ok(err); + + // More than one line of error output. + assert.ok(stderr.split('\n').length > 2); + + // Assert the script is mentioned in error output. + assert.ok(stderr.indexOf(script) >= 0); + + // Proxy the args for more tests. + callback(err, stdout, stderr); + + // Count the tests + exits++; + + console.log('.'); + }); +} + + +// Simple throw error +errExec('throws_error.js', function(err, stdout, stderr) { + assert.ok(/blah/.test(stderr)); +}); + + +// Trying to JSON.parse(undefined) +errExec('throws_error2.js', function(err, stdout, stderr) { + assert.ok(/SyntaxError/.test(stderr)); +}); + + +// Trying to JSON.parse(undefined) in nextTick +errExec('throws_error3.js', function(err, stdout, stderr) { + assert.ok(/SyntaxError/.test(stderr)); +}); + + +// throw ILLEGAL error +errExec('throws_error4.js', function(err, stdout, stderr) { + assert.ok(/\/\*\*/.test(stderr)); + assert.ok(/SyntaxError/.test(stderr)); +}); + + +process.on('exit', function() { + assert.equal(4, exits); +}); diff --git a/test/parallel/test-eval-require.js b/test/parallel/test-eval-require.js new file mode 100644 index 000000000..dfef416ce --- /dev/null +++ b/test/parallel/test-eval-require.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var path = require('path'); +var fs = require('fs'); + +var options = { + cwd: common.fixturesDir +}; +var child = spawn(process.execPath, ['-e', 'require("foo")'], options); +child.on('exit', function(code) { + assert.equal(code, 0); +}); + diff --git a/test/parallel/test-eval.js b/test/parallel/test-eval.js new file mode 100644 index 000000000..9c656a877 --- /dev/null +++ b/test/parallel/test-eval.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +require('../common'); +var util = require('util'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var success_count = 0; +var error_count = 0; + +var cmd = [process.execPath, '-e', '"console.error(process.argv)"', + 'foo', 'bar'].join(' '); +var expected = util.format([process.execPath, 'foo', 'bar']) + '\n'; +var child = exec(cmd, function(err, stdout, stderr) { + if (err) { + console.log(err.toString()); + ++error_count; + return; + } + assert.equal(stderr, expected); + ++success_count; +}); + +process.on('exit', function() { + assert.equal(1, success_count); + assert.equal(0, error_count); +}); + diff --git a/test/parallel/test-event-emitter-add-listeners.js b/test/parallel/test-event-emitter-add-listeners.js new file mode 100644 index 000000000..0806e049d --- /dev/null +++ b/test/parallel/test-event-emitter-add-listeners.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(); + +var events_new_listener_emited = []; +var listeners_new_listener_emited = []; +var times_hello_emited = 0; + +// sanity check +assert.equal(e.addListener, e.on); + +e.on('newListener', function(event, listener) { + console.log('newListener: ' + event); + events_new_listener_emited.push(event); + listeners_new_listener_emited.push(listener); +}); + +function hello(a, b) { + console.log('hello'); + times_hello_emited += 1; + assert.equal('a', a); + assert.equal('b', b); +} +e.on('hello', hello); + +var foo = function() {}; +e.once('foo', foo); + +console.log('start'); + +e.emit('hello', 'a', 'b'); + + +// just make sure that this doesn't throw: +var f = new events.EventEmitter(); +f.setMaxListeners(0); + + +process.on('exit', function() { + assert.deepEqual(['hello', 'foo'], events_new_listener_emited); + assert.deepEqual([hello, foo], listeners_new_listener_emited); + assert.equal(1, times_hello_emited); +}); + + diff --git a/test/parallel/test-event-emitter-check-listener-leaks.js b/test/parallel/test-event-emitter-check-listener-leaks.js new file mode 100644 index 000000000..d073e5de1 --- /dev/null +++ b/test/parallel/test-event-emitter-check-listener-leaks.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(); + +// default +for (var i = 0; i < 10; i++) { + e.on('default', function() {}); +} +assert.ok(!e._events['default'].hasOwnProperty('warned')); +e.on('default', function() {}); +assert.ok(e._events['default'].warned); + +// specific +e.setMaxListeners(5); +for (var i = 0; i < 5; i++) { + e.on('specific', function() {}); +} +assert.ok(!e._events['specific'].hasOwnProperty('warned')); +e.on('specific', function() {}); +assert.ok(e._events['specific'].warned); + +// only one +e.setMaxListeners(1); +e.on('only one', function() {}); +assert.ok(!e._events['only one'].hasOwnProperty('warned')); +e.on('only one', function() {}); +assert.ok(e._events['only one'].hasOwnProperty('warned')); + +// unlimited +e.setMaxListeners(0); +for (var i = 0; i < 1000; i++) { + e.on('unlimited', function() {}); +} +assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); + +// process-wide +events.EventEmitter.defaultMaxListeners = 42; +e = new events.EventEmitter(); + +for (var i = 0; i < 42; ++i) { + e.on('fortytwo', function() {}); +} +assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); +e.on('fortytwo', function() {}); +assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); +delete e._events['fortytwo'].warned; + +events.EventEmitter.defaultMaxListeners = 44; +e.on('fortytwo', function() {}); +assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); +e.on('fortytwo', function() {}); +assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); + +// but _maxListeners still has precedence over defaultMaxListeners +events.EventEmitter.defaultMaxListeners = 42; +e = new events.EventEmitter(); +e.setMaxListeners(1); +e.on('uno', function() {}); +assert.ok(!e._events['uno'].hasOwnProperty('warned')); +e.on('uno', function() {}); +assert.ok(e._events['uno'].hasOwnProperty('warned')); + +// chainable +assert.strictEqual(e, e.setMaxListeners(1)); diff --git a/test/parallel/test-event-emitter-get-max-listeners.js b/test/parallel/test-event-emitter-get-max-listeners.js new file mode 100644 index 000000000..8e47ef7a7 --- /dev/null +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -0,0 +1,34 @@ +// Copyright io.js contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var EventEmitter = require('events'); + +var emitter = new EventEmitter(); + +assert.strictEqual(emitter.getMaxListeners(), EventEmitter.defaultMaxListeners); + +emitter.setMaxListeners(0) +assert.strictEqual(emitter.getMaxListeners(), 0) + +emitter.setMaxListeners(3) +assert.strictEqual(emitter.getMaxListeners(), 3) diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js new file mode 100644 index 000000000..c6218e059 --- /dev/null +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -0,0 +1,61 @@ + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var EventEmitter = require('events').EventEmitter; +var assert = require('assert'); + +var e = new EventEmitter; +var fl; // foo listeners + +fl = e.listeners('foo'); +assert(Array.isArray(fl)); +assert(fl.length === 0); +assert.deepEqual(e._events, {}); + +e.on('foo', assert.fail); +fl = e.listeners('foo'); +assert(e._events.foo === assert.fail); +assert(Array.isArray(fl)); +assert(fl.length === 1); +assert(fl[0] === assert.fail); + +e.listeners('bar'); +assert(!e._events.hasOwnProperty('bar')); + +e.on('foo', assert.ok); +fl = e.listeners('foo'); + +assert(Array.isArray(e._events.foo)); +assert(e._events.foo.length === 2); +assert(e._events.foo[0] === assert.fail); +assert(e._events.foo[1] === assert.ok); + +assert(Array.isArray(fl)); +assert(fl.length === 2); +assert(fl[0] === assert.fail); +assert(fl[1] === assert.ok); + +console.log('ok'); diff --git a/test/parallel/test-event-emitter-listeners.js b/test/parallel/test-event-emitter-listeners.js new file mode 100644 index 000000000..3e622835b --- /dev/null +++ b/test/parallel/test-event-emitter-listeners.js @@ -0,0 +1,52 @@ + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +function listener() {} +function listener2() {} + +var e1 = new events.EventEmitter(); +e1.on('foo', listener); +var fooListeners = e1.listeners('foo'); +assert.deepEqual(e1.listeners('foo'), [listener]); +e1.removeAllListeners('foo'); +assert.deepEqual(e1.listeners('foo'), []); +assert.deepEqual(fooListeners, [listener]); + +var e2 = new events.EventEmitter(); +e2.on('foo', listener); +var e2ListenersCopy = e2.listeners('foo'); +assert.deepEqual(e2ListenersCopy, [listener]); +assert.deepEqual(e2.listeners('foo'), [listener]); +e2ListenersCopy.push(listener2); +assert.deepEqual(e2.listeners('foo'), [listener]); +assert.deepEqual(e2ListenersCopy, [listener, listener2]); + +var e3 = new events.EventEmitter(); +e3.on('foo', listener); +var e3ListenersCopy = e3.listeners('foo'); +e3.on('foo', listener2); +assert.deepEqual(e3.listeners('foo'), [listener, listener2]); +assert.deepEqual(e3ListenersCopy, [listener]); diff --git a/test/parallel/test-event-emitter-max-listeners.js b/test/parallel/test-event-emitter-max-listeners.js new file mode 100644 index 000000000..dfc3e1352 --- /dev/null +++ b/test/parallel/test-event-emitter-max-listeners.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var gotEvent = false; + +process.on('exit', function() { + assert(gotEvent); +}); + +var e = new events.EventEmitter(); + +e.on('maxListeners', function() { + gotEvent = true; +}); + +// Should not corrupt the 'maxListeners' queue. +e.setMaxListeners(42); + +assert.throws(function() { + e.setMaxListeners(NaN); +}); + +assert.throws(function() { + e.setMaxListeners(-1); +}); + +assert.throws(function() { + e.setMaxListeners("and even this"); +}); + +e.emit('maxListeners'); diff --git a/test/parallel/test-event-emitter-method-names.js b/test/parallel/test-event-emitter-method-names.js new file mode 100644 index 000000000..60d16b397 --- /dev/null +++ b/test/parallel/test-event-emitter-method-names.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var E = events.EventEmitter.prototype; +assert.equal(E.constructor.name, 'EventEmitter'); +assert.equal(E.on, E.addListener); // Same method. +Object.getOwnPropertyNames(E).forEach(function(name) { + if (name === 'constructor' || name === 'on') return; + if (typeof E[name] !== 'function') return; + assert.equal(E[name].name, name); +}); diff --git a/test/parallel/test-event-emitter-modify-in-emit.js b/test/parallel/test-event-emitter-modify-in-emit.js new file mode 100644 index 000000000..738af098c --- /dev/null +++ b/test/parallel/test-event-emitter-modify-in-emit.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var callbacks_called = []; + +var e = new events.EventEmitter(); + +function callback1() { + callbacks_called.push('callback1'); + e.on('foo', callback2); + e.on('foo', callback3); + e.removeListener('foo', callback1); +} + +function callback2() { + callbacks_called.push('callback2'); + e.removeListener('foo', callback2); +} + +function callback3() { + callbacks_called.push('callback3'); + e.removeListener('foo', callback3); +} + +e.on('foo', callback1); +assert.equal(1, e.listeners('foo').length); + +e.emit('foo'); +assert.equal(2, e.listeners('foo').length); +assert.deepEqual(['callback1'], callbacks_called); + +e.emit('foo'); +assert.equal(0, e.listeners('foo').length); +assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); + +e.emit('foo'); +assert.equal(0, e.listeners('foo').length); +assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); + +e.on('foo', callback1); +e.on('foo', callback2); +assert.equal(2, e.listeners('foo').length); +e.removeAllListeners('foo'); +assert.equal(0, e.listeners('foo').length); + +// Verify that removing callbacks while in emit allows emits to propagate to +// all listeners +callbacks_called = []; + +e.on('foo', callback2); +e.on('foo', callback3); +assert.equal(2, e.listeners('foo').length); +e.emit('foo'); +assert.deepEqual(['callback2', 'callback3'], callbacks_called); +assert.equal(0, e.listeners('foo').length); diff --git a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js new file mode 100644 index 000000000..79f14904e --- /dev/null +++ b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); +var domain = require('domain'); + +var errorCatched = false; + +var e = new events.EventEmitter(); + +var d = domain.create(); +d.add(e); +d.on('error', function (er) { + assert(er instanceof Error, 'error created'); + errorCatched = true; +}); + +e.emit('error'); + +process.on('exit', function () { + assert(errorCatched, 'error got caught'); +}); diff --git a/test/parallel/test-event-emitter-num-args.js b/test/parallel/test-event-emitter-num-args.js new file mode 100644 index 000000000..037c56965 --- /dev/null +++ b/test/parallel/test-event-emitter-num-args.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(), + num_args_emited = []; + +e.on('numArgs', function() { + var numArgs = arguments.length; + console.log('numArgs: ' + numArgs); + num_args_emited.push(numArgs); +}); + +console.log('start'); + +e.emit('numArgs'); +e.emit('numArgs', null); +e.emit('numArgs', null, null); +e.emit('numArgs', null, null, null); +e.emit('numArgs', null, null, null, null); +e.emit('numArgs', null, null, null, null, null); + +process.on('exit', function() { + assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited); +}); + + diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js new file mode 100644 index 000000000..2eaebcc7a --- /dev/null +++ b/test/parallel/test-event-emitter-once.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter(); +var times_hello_emited = 0; + +e.once('hello', function(a, b) { + times_hello_emited++; +}); + +e.emit('hello', 'a', 'b'); +e.emit('hello', 'a', 'b'); +e.emit('hello', 'a', 'b'); +e.emit('hello', 'a', 'b'); + +var remove = function() { + assert.fail(1, 0, 'once->foo should not be emitted', '!'); +}; + +e.once('foo', remove); +e.removeListener('foo', remove); +e.emit('foo'); + +process.on('exit', function() { + assert.equal(1, times_hello_emited); +}); + +var times_recurse_emitted = 0; + +e.once('e', function() { + e.emit('e'); + times_recurse_emitted++; +}); + +e.once('e', function() { + times_recurse_emitted++; +}); + +e.emit('e'); + +process.on('exit', function() { + assert.equal(2, times_recurse_emitted); +}); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js new file mode 100644 index 000000000..f9848d682 --- /dev/null +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + + +function expect(expected) { + var actual = []; + process.on('exit', function() { + assert.deepEqual(actual.sort(), expected.sort()); + }); + function listener(name) { + actual.push(name) + } + return common.mustCall(listener, expected.length); +} + +function listener() {} + +var e1 = new events.EventEmitter(); +e1.on('foo', listener); +e1.on('bar', listener); +e1.on('baz', listener); +e1.on('baz', listener); +var fooListeners = e1.listeners('foo'); +var barListeners = e1.listeners('bar'); +var bazListeners = e1.listeners('baz'); +e1.on('removeListener', expect(['bar', 'baz', 'baz'])); +e1.removeAllListeners('bar'); +e1.removeAllListeners('baz'); +assert.deepEqual(e1.listeners('foo'), [listener]); +assert.deepEqual(e1.listeners('bar'), []); +assert.deepEqual(e1.listeners('baz'), []); +// after calling removeAllListeners, +// the old listeners array should stay unchanged +assert.deepEqual(fooListeners, [listener]); +assert.deepEqual(barListeners, [listener]); +assert.deepEqual(bazListeners, [listener, listener]); +// after calling removeAllListeners, +// new listeners arrays are different from the old +assert.notEqual(e1.listeners('bar'), barListeners); +assert.notEqual(e1.listeners('baz'), bazListeners); + +var e2 = new events.EventEmitter(); +e2.on('foo', listener); +e2.on('bar', listener); +// expect LIFO order +e2.on('removeListener', expect(['foo', 'bar', 'removeListener'])); +e2.on('removeListener', expect(['foo', 'bar'])); +e2.removeAllListeners(); +console.error(e2); +assert.deepEqual([], e2.listeners('foo')); +assert.deepEqual([], e2.listeners('bar')); + +var e3 = new events.EventEmitter(); +e3.on('removeListener', listener); +// check for regression where removeAllListeners throws when +// there exists a removeListener listener, but there exists +// no listeners for the provided event type +assert.doesNotThrow(e3.removeAllListeners.bind(e3, 'foo')); diff --git a/test/parallel/test-event-emitter-remove-listeners.js b/test/parallel/test-event-emitter-remove-listeners.js new file mode 100644 index 000000000..78133a4f3 --- /dev/null +++ b/test/parallel/test-event-emitter-remove-listeners.js @@ -0,0 +1,84 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var count = 0; + +function listener1() { + console.log('listener1'); + count++; +} + +function listener2() { + console.log('listener2'); + count++; +} + +function listener3() { + console.log('listener3'); + count++; +} + +function remove1() { + assert(0); +} + +function remove2() { + assert(0); +} + +var e1 = new events.EventEmitter(); +e1.on('hello', listener1); +e1.on('removeListener', common.mustCall(function(name, cb) { + assert.equal(name, 'hello'); + assert.equal(cb, listener1); +})); +e1.removeListener('hello', listener1); +assert.deepEqual([], e1.listeners('hello')); + +var e2 = new events.EventEmitter(); +e2.on('hello', listener1); +e2.on('removeListener', assert.fail); +e2.removeListener('hello', listener2); +assert.deepEqual([listener1], e2.listeners('hello')); + +var e3 = new events.EventEmitter(); +e3.on('hello', listener1); +e3.on('hello', listener2); +e3.on('removeListener', common.mustCall(function(name, cb) { + assert.equal(name, 'hello'); + assert.equal(cb, listener1); +})); +e3.removeListener('hello', listener1); +assert.deepEqual([listener2], e3.listeners('hello')); + +var e4 = new events.EventEmitter(); +e4.on('removeListener', common.mustCall(function(name, cb) { + if (cb !== remove1) return; + this.removeListener('quux', remove2); + this.emit('quux'); +}, 2)); +e4.on('quux', remove1); +e4.on('quux', remove2); +e4.removeListener('quux', remove1); diff --git a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js new file mode 100644 index 000000000..604129796 --- /dev/null +++ b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var events = require('events'); + +var e = new events.EventEmitter; + +assert.deepEqual(e._events, {}); +e.setMaxListeners(5); +assert.deepEqual(e._events, {}); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js new file mode 100644 index 000000000..60b4bf387 --- /dev/null +++ b/test/parallel/test-event-emitter-subclass.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var EventEmitter = require('events').EventEmitter; +var util = require('util'); + +util.inherits(MyEE, EventEmitter); + +function MyEE(cb) { + this.once(1, cb); + this.emit(1); + this.removeAllListeners(); + EventEmitter.call(this); +} + +var called = false; +var myee = new MyEE(function() { + called = true; +}); + + +util.inherits(ErrorEE, EventEmitter); +function ErrorEE() { + this.emit('error', new Error('blerg')); +} + +assert.throws(function() { + new ErrorEE(); +}, /blerg/); + +process.on('exit', function() { + assert(called); + assert.deepEqual(myee._events, {}); + console.log('ok'); +}); + + +function MyEE2() { + EventEmitter.call(this); +} + +MyEE2.prototype = new EventEmitter(); + +var ee1 = new MyEE2(); +var ee2 = new MyEE2(); + +ee1.on('x', function () {}); + +assert.equal(EventEmitter.listenerCount(ee2, 'x'), 0); diff --git a/test/parallel/test-exception-handler.js b/test/parallel/test-exception-handler.js new file mode 100644 index 000000000..38137b834 --- /dev/null +++ b/test/parallel/test-exception-handler.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var MESSAGE = 'catch me if you can'; +var caughtException = false; + +process.on('uncaughtException', function(e) { + console.log('uncaught exception! 1'); + assert.equal(MESSAGE, e.message); + caughtException = true; +}); + +process.on('uncaughtException', function(e) { + console.log('uncaught exception! 2'); + assert.equal(MESSAGE, e.message); + caughtException = true; +}); + +setTimeout(function() { + throw new Error(MESSAGE); +}, 10); + +process.on('exit', function() { + console.log('exit'); + assert.equal(true, caughtException); +}); diff --git a/test/parallel/test-exception-handler2.js b/test/parallel/test-exception-handler2.js new file mode 100644 index 000000000..6b8afa909 --- /dev/null +++ b/test/parallel/test-exception-handler2.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +process.on('uncaughtException', function(err) { + console.log('Caught exception: ' + err); +}); + +var timeoutFired = false; +setTimeout(function() { + console.log('This will still run.'); + timeoutFired = true; +}, 500); + +process.on('exit', function() { + assert.ok(timeoutFired); +}); + +// Intentionally cause an exception, but don't catch it. +nonexistentFunc(); +console.log('This will not run.'); + diff --git a/test/parallel/test-exec-max-buffer.js b/test/parallel/test-exec-max-buffer.js new file mode 100644 index 000000000..3157fc73f --- /dev/null +++ b/test/parallel/test-exec-max-buffer.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var exec = require('child_process').exec; +var assert = require('assert'); + +var cmd = 'echo "hello world"'; + +exec(cmd, { maxBuffer: 5 }, function(err, stdout, stderr) { + assert.ok(err); + assert.ok(/maxBuffer/.test(err.message)); +}); diff --git a/test/parallel/test-file-read-noexist.js b/test/parallel/test-file-read-noexist.js new file mode 100644 index 000000000..aa5e761b4 --- /dev/null +++ b/test/parallel/test-file-read-noexist.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var got_error = false; + +var filename = path.join(common.fixturesDir, 'does_not_exist.txt'); +fs.readFile(filename, 'raw', function(err, content) { + if (err) { + got_error = true; + } else { + common.debug('cat returned some content: ' + content); + common.debug('this shouldn\'t happen as the file doesn\'t exist...'); + assert.equal(true, false); + } +}); + +process.on('exit', function() { + console.log('done'); + assert.equal(true, got_error); +}); diff --git a/test/parallel/test-file-write-stream.js b/test/parallel/test-file-write-stream.js new file mode 100644 index 000000000..d4d146a84 --- /dev/null +++ b/test/parallel/test-file-write-stream.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'); +var fs = require('fs'); +var fn = path.join(common.tmpDir, 'write.txt'); +var file = fs.createWriteStream(fn, { + highWaterMark: 10 + }); + +var EXPECTED = '012345678910'; + +var callbacks = { + open: -1, + drain: -2, + close: -1 + }; + +file + .on('open', function(fd) { + console.error('open!'); + callbacks.open++; + assert.equal('number', typeof fd); + }) + .on('error', function(err) { + throw err; + console.error('error!', err.stack); + }) + .on('drain', function() { + console.error('drain!', callbacks.drain); + callbacks.drain++; + if (callbacks.drain == -1) { + assert.equal(EXPECTED, fs.readFileSync(fn, 'utf8')); + file.write(EXPECTED); + } else if (callbacks.drain == 0) { + assert.equal(EXPECTED + EXPECTED, fs.readFileSync(fn, 'utf8')); + file.end(); + } + }) + .on('close', function() { + console.error('close!'); + assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); + + callbacks.close++; + assert.throws(function() { + console.error('write after end should not be allowed'); + file.write('should not work anymore'); + }); + + fs.unlinkSync(fn); + }); + +for (var i = 0; i < 11; i++) { + (function(i) { + file.write('' + i); + })(i); +} + +process.on('exit', function() { + for (var k in callbacks) { + assert.equal(0, callbacks[k], k + ' count off by ' + callbacks[k]); + } + console.log('ok'); +}); diff --git a/test/parallel/test-file-write-stream2.js b/test/parallel/test-file-write-stream2.js new file mode 100644 index 000000000..68361bb52 --- /dev/null +++ b/test/parallel/test-file-write-stream2.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'); +var fs = require('fs'); +var util = require('util'); + + +var filepath = path.join(common.tmpDir, 'write.txt'); +var file; + +var EXPECTED = '012345678910'; + +var cb_expected = 'write open drain write drain close error '; +var cb_occurred = ''; + +var countDrains = 0; + + +process.on('exit', function() { + removeTestFile(); + if (cb_occurred !== cb_expected) { + console.log(' Test callback events missing or out of order:'); + console.log(' expected: %j', cb_expected); + console.log(' occurred: %j', cb_occurred); + assert.strictEqual(cb_occurred, cb_expected, + 'events missing or out of order: "' + + cb_occurred + '" !== "' + cb_expected + '"'); + } else { + console.log('ok'); + } +}); + +function removeTestFile() { + try { + fs.unlinkSync(filepath); + } catch (e) {} +} + + +removeTestFile(); + +// drain at 0, return false at 10. +file = fs.createWriteStream(filepath, { + highWaterMark: 11 +}); + +file.on('open', function(fd) { + console.error('open'); + cb_occurred += 'open '; + assert.equal(typeof fd, 'number'); +}); + +file.on('drain', function() { + console.error('drain'); + cb_occurred += 'drain '; + ++countDrains; + if (countDrains === 1) { + console.error('drain=1, write again'); + assert.equal(fs.readFileSync(filepath, 'utf8'), EXPECTED); + console.error('ondrain write ret=%j', file.write(EXPECTED)); + cb_occurred += 'write '; + } else if (countDrains == 2) { + console.error('second drain, end'); + assert.equal(fs.readFileSync(filepath, 'utf8'), EXPECTED + EXPECTED); + file.end(); + } +}); + +file.on('close', function() { + cb_occurred += 'close '; + assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); + file.write('should not work anymore'); +}); + + +file.on('error', function(err) { + cb_occurred += 'error '; + assert.ok(err.message.indexOf('write after end') >= 0); +}); + + +for (var i = 0; i < 11; i++) { + var ret = file.write(i + ''); + console.error('%d %j', i, ret); + + // return false when i hits 10 + assert(ret === (i != 10)); +} +cb_occurred += 'write '; diff --git a/test/parallel/test-file-write-stream3.js b/test/parallel/test-file-write-stream3.js new file mode 100644 index 000000000..013946217 --- /dev/null +++ b/test/parallel/test-file-write-stream3.js @@ -0,0 +1,206 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + util = require('util'); + + +var filepath = path.join(common.tmpDir, 'write_pos.txt'); + + +var cb_expected = 'write open close write open close write open close ', + cb_occurred = ''; + +var fileDataInitial = 'abcdefghijklmnopqrstuvwxyz'; + +var fileDataExpected_1 = 'abcdefghijklmnopqrstuvwxyz'; +var fileDataExpected_2 = 'abcdefghij123456qrstuvwxyz'; +var fileDataExpected_3 = 'abcdefghij\u2026\u2026qrstuvwxyz'; + + +process.on('exit', function() { + removeTestFile(); + if (cb_occurred !== cb_expected) { + console.log(' Test callback events missing or out of order:'); + console.log(' expected: %j', cb_expected); + console.log(' occurred: %j', cb_occurred); + assert.strictEqual(cb_occurred, cb_expected, + 'events missing or out of order: "' + + cb_occurred + '" !== "' + cb_expected + '"'); + } +}); + +function removeTestFile() { + try { + fs.unlinkSync(filepath); + } catch (ex) { } +} + + +removeTestFile(); + + +function run_test_1() { + var file, buffer, options; + + options = {}; + file = fs.createWriteStream(filepath, options); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + + file.on('open', function(fd) { + cb_occurred += 'open '; + }); + + file.on('close', function() { + cb_occurred += 'close '; + console.log(' (debug: bytesWritten ', file.bytesWritten); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + assert.strictEqual(file.bytesWritten, buffer.length); + var fileData = fs.readFileSync(filepath, 'utf8'); + console.log(' (debug: file data ', fileData); + console.log(' (debug: expected ', fileDataExpected_1); + assert.equal(fileData, fileDataExpected_1); + + run_test_2(); + }); + + file.on('error', function(err) { + cb_occurred += 'error '; + console.log(' (debug: err event ', err); + throw err; + }); + + buffer = new Buffer(fileDataInitial); + file.write(buffer); + cb_occurred += 'write '; + + file.end(); +} + + +function run_test_2() { + var file, buffer, options; + + buffer = new Buffer('123456'); + + options = { start: 10, + flags: 'r+' }; + file = fs.createWriteStream(filepath, options); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + + file.on('open', function(fd) { + cb_occurred += 'open '; + }); + + file.on('close', function() { + cb_occurred += 'close '; + console.log(' (debug: bytesWritten ', file.bytesWritten); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + assert.strictEqual(file.bytesWritten, buffer.length); + var fileData = fs.readFileSync(filepath, 'utf8'); + console.log(' (debug: file data ', fileData); + console.log(' (debug: expected ', fileDataExpected_2); + assert.equal(fileData, fileDataExpected_2); + + run_test_3(); + }); + + file.on('error', function(err) { + cb_occurred += 'error '; + console.log(' (debug: err event ', err); + throw err; + }); + + file.write(buffer); + cb_occurred += 'write '; + + file.end(); +} + + +function run_test_3() { + var file, buffer, options; + + var data = '\u2026\u2026', // 3 bytes * 2 = 6 bytes in UTF-8 + fileData; + + options = { start: 10, + flags: 'r+' }; + file = fs.createWriteStream(filepath, options); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + + file.on('open', function(fd) { + cb_occurred += 'open '; + }); + + file.on('close', function() { + cb_occurred += 'close '; + console.log(' (debug: bytesWritten ', file.bytesWritten); + console.log(' (debug: start ', file.start); + console.log(' (debug: pos ', file.pos); + assert.strictEqual(file.bytesWritten, data.length * 3); + fileData = fs.readFileSync(filepath, 'utf8'); + console.log(' (debug: file data ', fileData); + console.log(' (debug: expected ', fileDataExpected_3); + assert.equal(fileData, fileDataExpected_3); + + run_test_4(); + }); + + file.on('error', function(err) { + cb_occurred += 'error '; + console.log(' (debug: err event ', err); + throw err; + }); + + file.write(data, 'utf8'); + cb_occurred += 'write '; + + file.end(); +} + + +function run_test_4() { + var file, options; + + options = { start: -5, + flags: 'r+' }; + + // Error: start must be >= zero + assert.throws( + function() { + file = fs.createWriteStream(filepath, options); + }, + /start must be/ + ); + +} + +run_test_1(); diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js new file mode 100644 index 000000000..3aa4b849f --- /dev/null +++ b/test/parallel/test-fs-access.js @@ -0,0 +1,99 @@ +// Copyright io.js contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var doesNotExist = __filename + '__this_should_not_exist'; +var readOnlyFile = path.join(common.tmpDir, 'read_only_file'); + +var removeFile = function(file) { + try { + fs.unlinkSync(file); + } catch (err) { + // Ignore error + } +}; + +var createReadOnlyFile = function(file) { + removeFile(file); + fs.writeFileSync(file, ''); + fs.chmodSync(file, 0444); +}; + +createReadOnlyFile(readOnlyFile); + +assert(typeof fs.F_OK === 'number'); +assert(typeof fs.R_OK === 'number'); +assert(typeof fs.W_OK === 'number'); +assert(typeof fs.X_OK === 'number'); + +fs.access(__filename, function(err) { + assert.strictEqual(err, null, 'error should not exist'); +}); + +fs.access(__filename, fs.R_OK, function(err) { + assert.strictEqual(err, null, 'error should not exist'); +}); + +fs.access(doesNotExist, function(err) { + assert.notEqual(err, null, 'error should exist'); + assert.strictEqual(err.code, 'ENOENT'); + assert.strictEqual(err.path, doesNotExist); +}); + +fs.access(readOnlyFile, fs.F_OK | fs.R_OK, function(err) { + assert.strictEqual(err, null, 'error should not exist'); +}); + +fs.access(readOnlyFile, fs.W_OK, function(err) { + assert.notEqual(err, null, 'error should exist'); + assert.strictEqual(err.path, readOnlyFile); +}); + +assert.throws(function() { + fs.access(100, fs.F_OK, function(err) {}); +}, /path must be a string/); + +assert.throws(function() { + fs.access(__filename, fs.F_OK); +}, /callback must be a function/); + +assert.doesNotThrow(function() { + fs.accessSync(__filename); +}); + +assert.doesNotThrow(function() { + var mode = fs.F_OK | fs.R_OK | fs.W_OK; + + fs.accessSync(__filename, mode); +}); + +assert.throws(function() { + fs.accessSync(doesNotExist); +}, function (err) { + return err.code === 'ENOENT' && err.path === doesNotExist; +}); + +process.on('exit', function() { + removeFile(readOnlyFile); +}); diff --git a/test/parallel/test-fs-append-file-sync.js b/test/parallel/test-fs-append-file-sync.js new file mode 100644 index 000000000..7bc6a0199 --- /dev/null +++ b/test/parallel/test-fs-append-file-sync.js @@ -0,0 +1,102 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var join = require('path').join; +var fs = require('fs'); + +var currentFileData = 'ABCD'; + +var num = 220; +var data = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; + +// test that empty file will be created and have content added +var filename = join(common.tmpDir, 'append-sync.txt'); + +common.error('appending to ' + filename); +fs.appendFileSync(filename, data); + +var fileData = fs.readFileSync(filename); +console.error('filedata is a ' + typeof fileData); + +assert.equal(Buffer.byteLength(data), fileData.length); + +// test that appends data to a non empty file +var filename2 = join(common.tmpDir, 'append-sync2.txt'); +fs.writeFileSync(filename2, currentFileData); + +common.error('appending to ' + filename2); +fs.appendFileSync(filename2, data); + +var fileData2 = fs.readFileSync(filename2); + +assert.equal(Buffer.byteLength(data) + currentFileData.length, + fileData2.length); + +// test that appendFileSync accepts buffers +var filename3 = join(common.tmpDir, 'append-sync3.txt'); +fs.writeFileSync(filename3, currentFileData); + +common.error('appending to ' + filename3); + +var buf = new Buffer(data, 'utf8'); +fs.appendFileSync(filename3, buf); + +var fileData3 = fs.readFileSync(filename3); + +assert.equal(buf.length + currentFileData.length, fileData3.length); + +// test that appendFile accepts numbers. +var filename4 = join(common.tmpDir, 'append-sync4.txt'); +fs.writeFileSync(filename4, currentFileData, { mode: m }); + +common.error('appending to ' + filename4); +var m = 0600; +fs.appendFileSync(filename4, num, { mode: m }); + +// windows permissions aren't unix +if (process.platform !== 'win32') { + var st = fs.statSync(filename4); + assert.equal(st.mode & 0700, m); +} + +var fileData4 = fs.readFileSync(filename4); + +assert.equal(Buffer.byteLength('' + num) + currentFileData.length, + fileData4.length); + +//exit logic for cleanup + +process.on('exit', function() { + common.error('done'); + + fs.unlinkSync(filename); + fs.unlinkSync(filename2); + fs.unlinkSync(filename3); + fs.unlinkSync(filename4); +}); diff --git a/test/parallel/test-fs-append-file.js b/test/parallel/test-fs-append-file.js new file mode 100644 index 000000000..450c8d3b9 --- /dev/null +++ b/test/parallel/test-fs-append-file.js @@ -0,0 +1,134 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var join = require('path').join; + +var filename = join(common.tmpDir, 'append.txt'); + +common.error('appending to ' + filename); + +var currentFileData = 'ABCD'; + +var n = 220; +var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; + +var ncallbacks = 0; + +// test that empty file will be created and have content added +fs.appendFile(filename, s, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file'); + + fs.readFile(filename, function(e, buffer) { + if (e) throw e; + common.error('file read'); + ncallbacks++; + assert.equal(Buffer.byteLength(s), buffer.length); + }); +}); + +// test that appends data to a non empty file +var filename2 = join(common.tmpDir, 'append2.txt'); +fs.writeFileSync(filename2, currentFileData); + +fs.appendFile(filename2, s, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file2'); + + fs.readFile(filename2, function(e, buffer) { + if (e) throw e; + common.error('file2 read'); + ncallbacks++; + assert.equal(Buffer.byteLength(s) + currentFileData.length, buffer.length); + }); +}); + +// test that appendFile accepts buffers +var filename3 = join(common.tmpDir, 'append3.txt'); +fs.writeFileSync(filename3, currentFileData); + +var buf = new Buffer(s, 'utf8'); +common.error('appending to ' + filename3); + +fs.appendFile(filename3, buf, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file3'); + + fs.readFile(filename3, function(e, buffer) { + if (e) throw e; + common.error('file3 read'); + ncallbacks++; + assert.equal(buf.length + currentFileData.length, buffer.length); + }); +}); + +// test that appendFile accepts numbers. +var filename4 = join(common.tmpDir, 'append4.txt'); +fs.writeFileSync(filename4, currentFileData); + +common.error('appending to ' + filename4); + +var m = 0600; +fs.appendFile(filename4, n, { mode: m }, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('appended to file4'); + + // windows permissions aren't unix + if (process.platform !== 'win32') { + var st = fs.statSync(filename4); + assert.equal(st.mode & 0700, m); + } + + fs.readFile(filename4, function(e, buffer) { + if (e) throw e; + common.error('file4 read'); + ncallbacks++; + assert.equal(Buffer.byteLength('' + n) + currentFileData.length, + buffer.length); + }); +}); + +process.on('exit', function() { + common.error('done'); + assert.equal(8, ncallbacks); + + fs.unlinkSync(filename); + fs.unlinkSync(filename2); + fs.unlinkSync(filename3); + fs.unlinkSync(filename4); +}); diff --git a/test/parallel/test-fs-chmod.js b/test/parallel/test-fs-chmod.js new file mode 100644 index 000000000..12fd820f3 --- /dev/null +++ b/test/parallel/test-fs-chmod.js @@ -0,0 +1,161 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var got_error = false; +var success_count = 0; +var mode_async; +var mode_sync; +var is_windows = process.platform === 'win32'; + +// Need to hijack fs.open/close to make sure that things +// get closed once they're opened. +fs._open = fs.open; +fs._openSync = fs.openSync; +fs.open = open; +fs.openSync = openSync; +fs._close = fs.close; +fs._closeSync = fs.closeSync; +fs.close = close; +fs.closeSync = closeSync; + +var openCount = 0; + +function open() { + openCount++; + return fs._open.apply(fs, arguments); +} + +function openSync() { + openCount++; + return fs._openSync.apply(fs, arguments); +} + +function close() { + openCount--; + return fs._close.apply(fs, arguments); +} + +function closeSync() { + openCount--; + return fs._closeSync.apply(fs, arguments); +} + + +// On Windows chmod is only able to manipulate read-only bit +if (is_windows) { + mode_async = 0400; // read-only + mode_sync = 0600; // read-write +} else { + mode_async = 0777; + mode_sync = 0644; +} + +var file1 = path.join(common.fixturesDir, 'a.js'), + file2 = path.join(common.fixturesDir, 'a1.js'); + +fs.chmod(file1, mode_async.toString(8), function(err) { + if (err) { + got_error = true; + } else { + console.log(fs.statSync(file1).mode); + + if (is_windows) { + assert.ok((fs.statSync(file1).mode & 0777) & mode_async); + } else { + assert.equal(mode_async, fs.statSync(file1).mode & 0777); + } + + fs.chmodSync(file1, mode_sync); + if (is_windows) { + assert.ok((fs.statSync(file1).mode & 0777) & mode_sync); + } else { + assert.equal(mode_sync, fs.statSync(file1).mode & 0777); + } + success_count++; + } +}); + +fs.open(file2, 'a', function(err, fd) { + if (err) { + got_error = true; + console.error(err.stack); + return; + } + fs.fchmod(fd, mode_async.toString(8), function(err) { + if (err) { + got_error = true; + } else { + console.log(fs.fstatSync(fd).mode); + + if (is_windows) { + assert.ok((fs.fstatSync(fd).mode & 0777) & mode_async); + } else { + assert.equal(mode_async, fs.fstatSync(fd).mode & 0777); + } + + fs.fchmodSync(fd, mode_sync); + if (is_windows) { + assert.ok((fs.fstatSync(fd).mode & 0777) & mode_sync); + } else { + assert.equal(mode_sync, fs.fstatSync(fd).mode & 0777); + } + success_count++; + fs.close(fd); + } + }); +}); + +// lchmod +if (fs.lchmod) { + var link = path.join(common.tmpDir, 'symbolic-link'); + + try { + fs.unlinkSync(link); + } catch (er) {} + fs.symlinkSync(file2, link); + + fs.lchmod(link, mode_async, function(err) { + if (err) { + got_error = true; + } else { + console.log(fs.lstatSync(link).mode); + assert.equal(mode_async, fs.lstatSync(link).mode & 0777); + + fs.lchmodSync(link, mode_sync); + assert.equal(mode_sync, fs.lstatSync(link).mode & 0777); + success_count++; + } + }); +} else { + success_count++; +} + + +process.on('exit', function() { + assert.equal(3, success_count); + assert.equal(0, openCount); + assert.equal(false, got_error); +}); + diff --git a/test/parallel/test-fs-empty-readStream.js b/test/parallel/test-fs-empty-readStream.js new file mode 100644 index 000000000..d181c2198 --- /dev/null +++ b/test/parallel/test-fs-empty-readStream.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var emptyFile = path.join(common.fixturesDir, 'empty.txt'); + +fs.open(emptyFile, 'r', function (error, fd) { + assert.ifError(error); + + var read = fs.createReadStream(emptyFile, { 'fd': fd }); + + read.once('data', function () { + throw new Error('data event should not emit'); + }); + + var readEmit = false; + read.once('end', function () { + readEmit = true; + console.error('end event 1'); + }); + + setTimeout(function () { + assert.equal(readEmit, true); + }, 50); +}); + +fs.open(emptyFile, 'r', function (error, fd) { + assert.ifError(error); + + var read = fs.createReadStream(emptyFile, { 'fd': fd }); + read.pause(); + + read.once('data', function () { + throw new Error('data event should not emit'); + }); + + var readEmit = false; + read.once('end', function () { + readEmit = true; + console.error('end event 2'); + }); + + setTimeout(function () { + assert.equal(readEmit, false); + }, 50); +}); diff --git a/test/parallel/test-fs-error-messages.js b/test/parallel/test-fs-error-messages.js new file mode 100644 index 000000000..16b5dd92b --- /dev/null +++ b/test/parallel/test-fs-error-messages.js @@ -0,0 +1,228 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + fn = path.join(common.fixturesDir, 'non-existent'), + existingFile = path.join(common.fixturesDir, 'exit.js'), + existingFile2 = path.join(common.fixturesDir, 'create-file.js'), + existingDir = path.join(common.fixturesDir, 'empty'), + existingDir2 = path.join(common.fixturesDir, 'keys'); + +// ASYNC_CALL + +fs.stat(fn, function(err) { + assert.equal(fn, err.path); + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.lstat(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.readlink(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.link(fn, 'foo', function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.link(existingFile, existingFile2, function(err) { + assert.ok(0 <= err.message.indexOf(existingFile2)); +}); + +fs.symlink(existingFile, existingFile2, function(err) { + assert.ok(0 <= err.message.indexOf(existingFile2)); +}); + +fs.unlink(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.rename(fn, 'foo', function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.rename(existingDir, existingDir2, function(err) { + assert.ok(0 <= err.message.indexOf(existingDir2)); +}); + +fs.rmdir(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.mkdir(existingFile, 0666, function(err) { + assert.ok(0 <= err.message.indexOf(existingFile)); +}); + +fs.rmdir(existingFile, function(err) { + assert.ok(0 <= err.message.indexOf(existingFile)); +}); + +fs.chmod(fn, 0666, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.open(fn, 'r', 0666, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +fs.readFile(fn, function(err) { + assert.ok(0 <= err.message.indexOf(fn)); +}); + +// Sync + +var errors = [], + expected = 0; + +try { + ++expected; + fs.statSync(fn); +} catch (err) { + errors.push('stat'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.mkdirSync(existingFile, 0666); +} catch (err) { + errors.push('mkdir'); + assert.ok(0 <= err.message.indexOf(existingFile)); +} + +try { + ++expected; + fs.chmodSync(fn, 0666); +} catch (err) { + errors.push('chmod'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.lstatSync(fn); +} catch (err) { + errors.push('lstat'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.readlinkSync(fn); +} catch (err) { + errors.push('readlink'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.linkSync(fn, 'foo'); +} catch (err) { + errors.push('link'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.linkSync(existingFile, existingFile2); +} catch (err) { + errors.push('link'); + assert.ok(0 <= err.message.indexOf(existingFile2)); +} + +try { + ++expected; + fs.symlinkSync(existingFile, existingFile2); +} catch (err) { + errors.push('symlink'); + assert.ok(0 <= err.message.indexOf(existingFile2)); +} + +try { + ++expected; + fs.unlinkSync(fn); +} catch (err) { + errors.push('unlink'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.rmdirSync(fn); +} catch (err) { + errors.push('rmdir'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.rmdirSync(existingFile); +} catch (err) { + errors.push('rmdir'); + assert.ok(0 <= err.message.indexOf(existingFile)); +} + +try { + ++expected; + fs.openSync(fn, 'r'); +} catch (err) { + errors.push('opens'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.renameSync(fn, 'foo'); +} catch (err) { + errors.push('rename'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +try { + ++expected; + fs.renameSync(existingDir, existingDir2); +} catch (err) { + errors.push('rename'); + assert.ok(0 <= err.message.indexOf(existingDir2)); +} + +try { + ++expected; + fs.readdirSync(fn); +} catch (err) { + errors.push('readdir'); + assert.ok(0 <= err.message.indexOf(fn)); +} + +process.on('exit', function() { + assert.equal(expected, errors.length, + 'Test fs sync exceptions raised, got ' + errors.length + + ' expected ' + expected); +}); diff --git a/test/parallel/test-fs-exists.js b/test/parallel/test-fs-exists.js new file mode 100644 index 000000000..377573056 --- /dev/null +++ b/test/parallel/test-fs-exists.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var f = __filename; +var exists; +var doesNotExist; + +fs.exists(f, function(y) { + exists = y; +}); + +fs.exists(f + '-NO', function(y) { + doesNotExist = y; +}); + +assert(fs.existsSync(f)); +assert(!fs.existsSync(f + '-NO')); + +process.on('exit', function() { + assert.strictEqual(exists, true); + assert.strictEqual(doesNotExist, false); +}); diff --git a/test/parallel/test-fs-fsync.js b/test/parallel/test-fs-fsync.js new file mode 100644 index 000000000..e624ed7d6 --- /dev/null +++ b/test/parallel/test-fs-fsync.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'); +var fs = require('fs'); +var successes = 0; + +var file = path.join(common.fixturesDir, 'a.js'); + +common.error('open ' + file); + +fs.open(file, 'a', 0777, function(err, fd) { + common.error('fd ' + fd); + if (err) throw err; + + fs.fdatasyncSync(fd); + common.error('fdatasync SYNC: ok'); + successes++; + + fs.fsyncSync(fd); + common.error('fsync SYNC: ok'); + successes++; + + fs.fdatasync(fd, function(err) { + if (err) throw err; + common.error('fdatasync ASYNC: ok'); + successes++; + fs.fsync(fd, function(err) { + if (err) throw err; + common.error('fsync ASYNC: ok'); + successes++; + }); + }); +}); + +process.on('exit', function() { + assert.equal(4, successes); +}); diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js new file mode 100644 index 000000000..67f042976 --- /dev/null +++ b/test/parallel/test-fs-long-path.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var fs = require('fs'); +var path = require('path'); +var assert = require('assert'); + +var successes = 0; + +// make a path that will be at least 260 chars long. +var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); +var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); +var fullPath = path.resolve(fileName); + +try { + fs.unlinkSync(fullPath); +} +catch (e) { + // Ignore. +} + +console.log({ + filenameLength: fileName.length, + fullPathLength: fullPath.length +}); + +fs.writeFile(fullPath, 'ok', function(err) { + if (err) throw err; + successes++; + + fs.stat(fullPath, function(err, stats) { + if (err) throw err; + successes++; + }); +}); + +process.on('exit', function() { + fs.unlinkSync(fullPath); + assert.equal(2, successes); +}); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js new file mode 100644 index 000000000..d99cd371b --- /dev/null +++ b/test/parallel/test-fs-mkdir.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +function unlink(pathname) { + try { + fs.rmdirSync(pathname); + } catch (e) { + } +} + +(function() { + var ncalls = 0; + var pathname = common.tmpDir + '/test1'; + + unlink(pathname); + + fs.mkdir(pathname, function(err) { + assert.equal(err, null); + assert.equal(fs.existsSync(pathname), true); + ncalls++; + }); + + process.on('exit', function() { + unlink(pathname); + assert.equal(ncalls, 1); + }); +})(); + +(function() { + var ncalls = 0; + var pathname = common.tmpDir + '/test2'; + + unlink(pathname); + + fs.mkdir(pathname, 511 /*=0777*/, function(err) { + assert.equal(err, null); + assert.equal(fs.existsSync(pathname), true); + ncalls++; + }); + + process.on('exit', function() { + unlink(pathname); + assert.equal(ncalls, 1); + }); +})(); + +(function() { + var pathname = common.tmpDir + '/test3'; + + unlink(pathname); + fs.mkdirSync(pathname); + + var exists = fs.existsSync(pathname); + unlink(pathname); + + assert.equal(exists, true); +})(); + +// Keep the event loop alive so the async mkdir() requests +// have a chance to run (since they don't ref the event loop). +process.nextTick(function() {}); diff --git a/test/parallel/test-fs-non-number-arguments-throw.js b/test/parallel/test-fs-non-number-arguments-throw.js new file mode 100644 index 000000000..7a1e7bdb5 --- /dev/null +++ b/test/parallel/test-fs-non-number-arguments-throw.js @@ -0,0 +1,24 @@ +var assert = require('assert'), + fs = require('fs'), + saneEmitter, + sanity = 'ire(\'assert\')'; + +saneEmitter = fs.createReadStream(__filename, { start: 17, end: 29 }); + +assert.throws(function () { + fs.createReadStream(__filename, { start: "17", end: 29 }); +}, "start as string didn't throw an error for createReadStream"); + +assert.throws(function () { + fs.createReadStream(__filename, { start: 17, end: "29" }); +}, "end as string didn't throw an error"); + +assert.throws(function () { + fs.createWriteStream(__filename, { start: "17" }); +}, "start as string didn't throw an error for createWriteStream"); + +saneEmitter.on('data', function (data) { + // a sanity check when using numbers instead of strings + assert.strictEqual(sanity, data.toString('utf8'), 'read ' + + data.toString('utf8') + ' instead of ' + sanity); +}); diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js new file mode 100644 index 000000000..5dec223ba --- /dev/null +++ b/test/parallel/test-fs-null-bytes.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +function check(async, sync) { + var expected = /Path must be a string without null bytes./; + var argsSync = Array.prototype.slice.call(arguments, 2); + var argsAsync = argsSync.concat(function(er) { + assert(er && er.message.match(expected)); + }); + + if (sync) + assert.throws(function() { + console.error(sync.name, argsSync); + sync.apply(null, argsSync); + }, expected); + + if (async) + async.apply(null, argsAsync); +} + +check(fs.appendFile, fs.appendFileSync, 'foo\u0000bar'); +check(fs.chmod, fs.chmodSync, 'foo\u0000bar', '0644'); +check(fs.chown, fs.chownSync, 'foo\u0000bar', 12, 34); +check(fs.link, fs.linkSync, 'foo\u0000bar', 'foobar'); +check(fs.link, fs.linkSync, 'foobar', 'foo\u0000bar'); +check(fs.lstat, fs.lstatSync, 'foo\u0000bar'); +check(fs.mkdir, fs.mkdirSync, 'foo\u0000bar', '0755'); +check(fs.open, fs.openSync, 'foo\u0000bar', 'r'); +check(fs.readFile, fs.readFileSync, 'foo\u0000bar'); +check(fs.readdir, fs.readdirSync, 'foo\u0000bar'); +check(fs.readlink, fs.readlinkSync, 'foo\u0000bar'); +check(fs.realpath, fs.realpathSync, 'foo\u0000bar'); +check(fs.rename, fs.renameSync, 'foo\u0000bar', 'foobar'); +check(fs.rename, fs.renameSync, 'foobar', 'foo\u0000bar'); +check(fs.rmdir, fs.rmdirSync, 'foo\u0000bar'); +check(fs.stat, fs.statSync, 'foo\u0000bar'); +check(fs.symlink, fs.symlinkSync, 'foo\u0000bar', 'foobar'); +check(fs.symlink, fs.symlinkSync, 'foobar', 'foo\u0000bar'); +check(fs.truncate, fs.truncateSync, 'foo\u0000bar'); +check(fs.unlink, fs.unlinkSync, 'foo\u0000bar'); +check(null, fs.unwatchFile, 'foo\u0000bar', assert.fail); +check(fs.utimes, fs.utimesSync, 'foo\u0000bar', 0, 0); +check(null, fs.watch, 'foo\u0000bar', assert.fail); +check(null, fs.watchFile, 'foo\u0000bar', assert.fail); +check(fs.writeFile, fs.writeFileSync, 'foo\u0000bar'); + +// an 'error' for exists means that it doesn't exist. +// one of many reasons why this file is the absolute worst. +fs.exists('foo\u0000bar', function(exists) { + assert(!exists); +}); +assert(!fs.existsSync('foo\u0000bar')); + diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js new file mode 100644 index 000000000..e1c6c3be9 --- /dev/null +++ b/test/parallel/test-fs-open-flags.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var constants = require('constants'); +var fs = require('fs'); + +var O_APPEND = constants.O_APPEND || 0; +var O_CREAT = constants.O_CREAT || 0; +var O_DIRECTORY = constants.O_DIRECTORY || 0; +var O_EXCL = constants.O_EXCL || 0; +var O_NOCTTY = constants.O_NOCTTY || 0; +var O_NOFOLLOW = constants.O_NOFOLLOW || 0; +var O_RDONLY = constants.O_RDONLY || 0; +var O_RDWR = constants.O_RDWR || 0; +var O_SYMLINK = constants.O_SYMLINK || 0; +var O_SYNC = constants.O_SYNC || 0; +var O_TRUNC = constants.O_TRUNC || 0; +var O_WRONLY = constants.O_WRONLY || 0; + +assert.equal(fs._stringToFlags('r'), O_RDONLY); +assert.equal(fs._stringToFlags('r+'), O_RDWR); +assert.equal(fs._stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); +assert.equal(fs._stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); +assert.equal(fs._stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); +assert.equal(fs._stringToFlags('a+'), O_APPEND | O_CREAT | O_RDWR); + +assert.equal(fs._stringToFlags('wx'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('xw'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); +assert.equal(fs._stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); +assert.equal(fs._stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.equal(fs._stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); +assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); + +('+ +a +r +w rw wa war raw r++ a++ w++' + + 'x +x x+ rx rx+ wxx wax xwx xxx').split(' ').forEach(function(flags) { + assert.throws(function() { fs._stringToFlags(flags); }); +}); diff --git a/test/parallel/test-fs-open.js b/test/parallel/test-fs-open.js new file mode 100644 index 000000000..e334de989 --- /dev/null +++ b/test/parallel/test-fs-open.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var constants = require('constants'); +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var caughtException = false; +try { + // should throw ENOENT, not EBADF + // see https://github.com/joyent/node/pull/1228 + fs.openSync('/path/to/file/that/does/not/exist', 'r'); +} +catch (e) { + assert.equal(e.code, 'ENOENT'); + caughtException = true; +} +assert.ok(caughtException); + +var openFd; +fs.open(__filename, 'r', function(err, fd) { + if (err) { + throw err; + } + openFd = fd; +}); + +var openFd2; +fs.open(__filename, 'rs', function(err, fd) { + if (err) { + throw err; + } + openFd2 = fd; +}); + +process.on('exit', function() { + assert.ok(openFd); + assert.ok(openFd2); +}); + diff --git a/test/parallel/test-fs-read-buffer.js b/test/parallel/test-fs-read-buffer.js new file mode 100644 index 000000000..96f700363 --- /dev/null +++ b/test/parallel/test-fs-read-buffer.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + Buffer = require('buffer').Buffer, + fs = require('fs'), + filepath = path.join(common.fixturesDir, 'x.txt'), + fd = fs.openSync(filepath, 'r'), + expected = 'xyz\n', + bufferAsync = new Buffer(expected.length), + bufferSync = new Buffer(expected.length), + readCalled = 0; + +fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { + readCalled++; + + assert.equal(bytesRead, expected.length); + assert.deepEqual(bufferAsync, new Buffer(expected)); +}); + +var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); +assert.deepEqual(bufferSync, new Buffer(expected)); +assert.equal(r, expected.length); + +process.on('exit', function() { + assert.equal(readCalled, 1); +}); diff --git a/test/parallel/test-fs-read-file-sync-hostname.js b/test/parallel/test-fs-read-file-sync-hostname.js new file mode 100644 index 000000000..758e2aedd --- /dev/null +++ b/test/parallel/test-fs-read-file-sync-hostname.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +// test reading from hostname +if (process.platform === 'linux2') { + var hostname = fs.readFileSync('/proc/sys/kernel/hostname'); + assert.ok(hostname.length > 0); +} diff --git a/test/parallel/test-fs-read-file-sync.js b/test/parallel/test-fs-read-file-sync.js new file mode 100644 index 000000000..518d32cc1 --- /dev/null +++ b/test/parallel/test-fs-read-file-sync.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var fn = path.join(common.fixturesDir, 'elipses.txt'); + +var s = fs.readFileSync(fn, 'utf8'); +for (var i = 0; i < s.length; i++) { + assert.equal('\u2026', s[i]); +} +assert.equal(10000, s.length); diff --git a/test/parallel/test-fs-read-stream-err.js b/test/parallel/test-fs-read-stream-err.js new file mode 100644 index 000000000..54aa21799 --- /dev/null +++ b/test/parallel/test-fs-read-stream-err.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var stream = fs.createReadStream(__filename, { + bufferSize: 64 +}); +var err = new Error('BAM'); + +stream.on('error', common.mustCall(function errorHandler(err_) { + console.error('error event'); + process.nextTick(function() { + assert.equal(stream.fd, null); + assert.equal(err_, err); + }); +})); + +fs.close = common.mustCall(function(fd_, cb) { + assert.equal(fd_, stream.fd); + process.nextTick(cb); +}); + +var read = fs.read; +fs.read = function() { + // first time is ok. + read.apply(fs, arguments); + // then it breaks + fs.read = function() { + var cb = arguments[arguments.length - 1]; + process.nextTick(function() { + cb(err); + }); + // and should not be called again! + fs.read = function() { + throw new Error('BOOM!'); + }; + }; +}; + +stream.on('data', function(buf) { + stream.on('data', assert.fail); // no more 'data' events should follow +}); diff --git a/test/parallel/test-fs-read-stream-fd.js b/test/parallel/test-fs-read-stream-fd.js new file mode 100644 index 000000000..835ed9727 --- /dev/null +++ b/test/parallel/test-fs-read-stream-fd.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); +var assert = require('assert'); +var path = require('path'); + +var common = require('../common'); + +var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); +var input = 'hello world'; +var output = ''; +var fd, stream; + +fs.writeFileSync(file, input); +fd = fs.openSync(file, 'r'); + +stream = fs.createReadStream(null, { fd: fd, encoding: 'utf8' }); +stream.on('data', function(data) { + output += data; +}); + +process.on('exit', function() { + fs.unlinkSync(file); + assert.equal(output, input); +}); diff --git a/test/parallel/test-fs-read-stream-resume.js b/test/parallel/test-fs-read-stream-resume.js new file mode 100644 index 000000000..c3ace49e9 --- /dev/null +++ b/test/parallel/test-fs-read-stream-resume.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var path = require('path'); + +var file = path.join(common.fixturesDir, 'x.txt'); +var data = ''; +var first = true; + +var stream = fs.createReadStream(file); +stream.setEncoding('utf8'); +stream.on('data', function(chunk) { + data += chunk; + if (first) { + first = false; + stream.resume(); + } +}); + +process.nextTick(function() { + stream.pause(); + setTimeout(function() { + stream.resume(); + }, 100); +}); + +process.on('exit', function() { + assert.equal(data, 'xyz\n'); +}); diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js new file mode 100644 index 000000000..4d1eebb2c --- /dev/null +++ b/test/parallel/test-fs-read-stream.js @@ -0,0 +1,197 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +// TODO Improved this test. test_ca.pem is too small. A proper test would +// great a large utf8 (with multibyte chars) file and stream it in, +// performing sanity checks throughout. + +var path = require('path'); +var fs = require('fs'); +var fn = path.join(common.fixturesDir, 'elipses.txt'); +var rangeFile = path.join(common.fixturesDir, 'x.txt'); + +var callbacks = { open: 0, end: 0, close: 0 }; + +var paused = false; + +var file = fs.ReadStream(fn); + +file.on('open', function(fd) { + file.length = 0; + callbacks.open++; + assert.equal('number', typeof fd); + assert.ok(file.readable); + + // GH-535 + file.pause(); + file.resume(); + file.pause(); + file.resume(); +}); + +file.on('data', function(data) { + assert.ok(data instanceof Buffer); + assert.ok(!paused); + file.length += data.length; + + paused = true; + file.pause(); + + setTimeout(function() { + paused = false; + file.resume(); + }, 10); +}); + + +file.on('end', function(chunk) { + callbacks.end++; +}); + + +file.on('close', function() { + callbacks.close++; + + //assert.equal(fs.readFileSync(fn), fileContent); +}); + +var file3 = fs.createReadStream(fn, {encoding: 'utf8'}); +file3.length = 0; +file3.on('data', function(data) { + assert.equal('string', typeof(data)); + file3.length += data.length; + + for (var i = 0; i < data.length; i++) { + // http://www.fileformat.info/info/unicode/char/2026/index.htm + assert.equal('\u2026', data[i]); + } +}); + +file3.on('close', function() { + callbacks.close++; +}); + +process.on('exit', function() { + assert.equal(1, callbacks.open); + assert.equal(1, callbacks.end); + assert.equal(2, callbacks.close); + assert.equal(30000, file.length); + assert.equal(10000, file3.length); + console.error('ok'); +}); + +var file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); +var contentRead = ''; +file4.on('data', function(data) { + contentRead += data.toString('utf-8'); +}); +file4.on('end', function(data) { + assert.equal(contentRead, 'yz'); +}); + +var file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); +file5.data = ''; +file5.on('data', function(data) { + file5.data += data.toString('utf-8'); +}); +file5.on('end', function() { + assert.equal(file5.data, 'yz\n'); +}); + +// https://github.com/joyent/node/issues/2320 +var file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); +file6.data = ''; +file6.on('data', function(data) { + file6.data += data.toString('utf-8'); +}); +file6.on('end', function() { + assert.equal(file6.data, 'yz\n'); +}); + +assert.throws(function() { + fs.createReadStream(rangeFile, {start: 10, end: 2}); +}, /start must be <= end/); + +var stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); +stream.data = ''; + +stream.on('data', function(chunk) { + stream.data += chunk; +}); + +stream.on('end', function() { + assert.equal('x', stream.data); +}); + +// pause and then resume immediately. +var pauseRes = fs.createReadStream(rangeFile); +pauseRes.pause(); +pauseRes.resume(); + +var file7 = fs.createReadStream(rangeFile, {autoClose: false }); +file7.on('data', function() {}); +file7.on('end', function() { + process.nextTick(function() { + assert(!file7.closed); + assert(!file7.destroyed); + file7Next(); + }); +}); + +function file7Next(){ + // This will tell us if the fd is usable again or not. + file7 = fs.createReadStream(null, {fd: file7.fd, start: 0 }); + file7.data = ''; + file7.on('data', function(data) { + file7.data += data; + }); + file7.on('end', function(err) { + assert.equal(file7.data, 'xyz\n'); + }); +} + +// Just to make sure autoClose won't close the stream because of error. +var file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); +file8.on('data', function() {}); +file8.on('error', common.mustCall(function() {})); + +// Make sure stream is destroyed when file does not exist. +var file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); +file9.on('data', function() {}); +file9.on('error', common.mustCall(function() {})); + +process.on('exit', function() { + assert(file7.closed); + assert(file7.destroyed); + + assert(!file8.closed); + assert(!file8.destroyed); + assert(file8.fd); + + assert(!file9.closed); + assert(file9.destroyed); +}); diff --git a/test/parallel/test-fs-read.js b/test/parallel/test-fs-read.js new file mode 100644 index 000000000..4a90f9091 --- /dev/null +++ b/test/parallel/test-fs-read.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + fs = require('fs'), + filepath = path.join(common.fixturesDir, 'x.txt'), + fd = fs.openSync(filepath, 'r'), + expected = 'xyz\n', + readCalled = 0; + +fs.read(fd, expected.length, 0, 'utf-8', function(err, str, bytesRead) { + readCalled++; + + assert.ok(!err); + assert.equal(str, expected); + assert.equal(bytesRead, expected.length); +}); + +var r = fs.readSync(fd, expected.length, 0, 'utf-8'); +assert.equal(r[0], expected); +assert.equal(r[1], expected.length); + +process.on('exit', function() { + assert.equal(readCalled, 1); +}); diff --git a/test/parallel/test-fs-readfile-empty.js b/test/parallel/test-fs-readfile-empty.js new file mode 100644 index 000000000..31b83567e --- /dev/null +++ b/test/parallel/test-fs-readfile-empty.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'), + fn = path.join(common.fixturesDir, 'empty.txt'); + +fs.readFile(fn, function(err, data) { + assert.ok(data); +}); + +fs.readFile(fn, 'utf8', function(err, data) { + assert.strictEqual('', data); +}); + +assert.ok(fs.readFileSync(fn)); +assert.strictEqual('', fs.readFileSync(fn, 'utf8')); diff --git a/test/parallel/test-fs-readfile-error.js b/test/parallel/test-fs-readfile-error.js new file mode 100644 index 000000000..72e1e2e7f --- /dev/null +++ b/test/parallel/test-fs-readfile-error.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; +var path = require('path'); + +var callbacks = 0; + +function test(env, cb) { + var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js'); + var execPath = process.execPath + ' ' + filename; + var options = { env: env || {} }; + exec(execPath, options, function(err, stdout, stderr) { + assert(err); + assert.equal(stdout, ''); + assert.notEqual(stderr, ''); + cb('' + stderr); + }); +} + +test({ NODE_DEBUG: '' }, function(data) { + assert(/EISDIR/.test(data)); + assert(!/test-fs-readfile-error/.test(data)); + callbacks++; +}); + +test({ NODE_DEBUG: 'fs' }, function(data) { + assert(/EISDIR/.test(data)); + assert(/test-fs-readfile-error/.test(data)); + callbacks++; +}); + +process.on('exit', function() { + assert.equal(callbacks, 2); +}); diff --git a/test/parallel/test-fs-readfile-pipe.js b/test/parallel/test-fs-readfile-pipe.js new file mode 100644 index 000000000..8ca165144 --- /dev/null +++ b/test/parallel/test-fs-readfile-pipe.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// simulate `cat readfile.js | node readfile.js` + +// TODO: Have some way to make this work on windows. +if (process.platform === 'win32') { + console.error('No /dev/stdin on windows. Skipping test.'); + process.exit(); +} + +var fs = require('fs'); + +var dataExpected = fs.readFileSync(__filename, 'utf8'); + +if (process.argv[2] === 'child') { + fs.readFile('/dev/stdin', function(er, data) { + if (er) throw er; + process.stdout.write(data); + }); + return; +} + +var exec = require('child_process').exec; +var f = JSON.stringify(__filename); +var node = JSON.stringify(process.execPath); +var cmd = 'cat ' + f + ' | ' + node + ' ' + f + ' child'; +exec(cmd, function(err, stdout, stderr) { + if (err) console.error(err); + assert(!err, 'it exits normally'); + assert(stdout === dataExpected, 'it reads the file and outputs it'); + assert(stderr === '', 'it does not write to stderr'); + console.log('ok'); +}); diff --git a/test/parallel/test-fs-readfile-unlink.js b/test/parallel/test-fs-readfile-unlink.js new file mode 100644 index 000000000..0bb4a67f7 --- /dev/null +++ b/test/parallel/test-fs-readfile-unlink.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + common = require('../common'), + fs = require('fs'), + path = require('path'), + dirName = path.resolve(common.fixturesDir, 'test-readfile-unlink'), + fileName = path.resolve(dirName, 'test.bin'); + +var buf = new Buffer(512 * 1024); +buf.fill(42); + +try { + fs.mkdirSync(dirName); +} catch (e) { + // Ignore if the directory already exists. + if (e.code != 'EEXIST') throw e; +} + +fs.writeFileSync(fileName, buf); + +fs.readFile(fileName, function(err, data) { + assert.ifError(err); + assert(data.length == buf.length); + assert.strictEqual(buf[0], 42); + + fs.unlinkSync(fileName); + fs.rmdirSync(dirName); +}); diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js new file mode 100644 index 000000000..60f41226f --- /dev/null +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var dataExpected = fs.readFileSync(__filename, 'utf8'); + +// sometimes stat returns size=0, but it's a lie. +fs._fstat = fs.fstat; +fs._fstatSync = fs.fstatSync; + +fs.fstat = function(fd, cb) { + fs._fstat(fd, function(er, st) { + if (er) return cb(er); + st.size = 0; + return cb(er, st); + }); +}; + +fs.fstatSync = function(fd) { + var st = fs._fstatSync; + st.size = 0; + return st; +}; + +var d = fs.readFileSync(__filename, 'utf8'); +assert.equal(d, dataExpected); + +var called = false; +fs.readFile(__filename, 'utf8', function (er, d) { + assert.equal(d, dataExpected); + called = true; +}); + +process.on('exit', function() { + assert(called); + console.log("ok"); +}); diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js new file mode 100644 index 000000000..9b02ae717 --- /dev/null +++ b/test/parallel/test-fs-realpath.js @@ -0,0 +1,611 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var exec = require('child_process').exec; +var async_completed = 0, async_expected = 0, unlink = []; +var isWindows = process.platform === 'win32'; +var skipSymlinks = false; + +var root = '/'; +if (isWindows) { + // something like "C:\\" + root = process.cwd().substr(0, 3); + + // On Windows, creating symlinks requires admin privileges. + // We'll only try to run symlink test if we have enough privileges. + try { + exec('whoami /priv', function(err, o) { + if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { + skipSymlinks = true; + } + runTest(); + }); + } catch (er) { + // better safe than sorry + skipSymlinks = true; + process.nextTick(runTest); + } +} else { + process.nextTick(runTest); +} + + +function tmp(p) { + return path.join(common.tmpDir, p); +} + +var fixturesAbsDir = common.fixturesDir; +var tmpAbsDir = common.tmpDir; + +console.error("absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir); + +function asynctest(testBlock, args, callback, assertBlock) { + async_expected++; + testBlock.apply(testBlock, args.concat(function(err) { + var ignoreError = false; + if (assertBlock) { + try { + ignoreError = assertBlock.apply(assertBlock, arguments); + } + catch (e) { + err = e; + } + } + async_completed++; + callback(ignoreError ? null : err); + })); +} + +// sub-tests: +function test_simple_error_callback(cb) { + var ncalls = 0; + + fs.realpath('/this/path/does/not/exist', function(err, s) { + assert(err); + assert(!s); + ncalls++; + cb(); + }); + + process.on('exit', function() { + assert.equal(ncalls, 1); + }); +} + +function test_simple_relative_symlink(callback) { + console.log('test_simple_relative_symlink'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var entry = common.tmpDir + '/symlink', + expected = common.tmpDir + '/cycles/root.js'; + [ + [entry, '../' + common.tmpDirName + '/cycles/root.js'] + ].forEach(function(t) { + try {fs.unlinkSync(t[0]);}catch (e) {} + console.log('fs.symlinkSync(%j, %j, %j)', t[1], t[0], 'file'); + fs.symlinkSync(t[1], t[0], 'file'); + unlink.push(t[0]); + }); + var result = fs.realpathSync(entry); + assert.equal(result, path.resolve(expected), + 'got ' + common.inspect(result) + ' expected ' + + common.inspect(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(expected)); + }); +} + +function test_simple_absolute_symlink(callback) { + console.log('test_simple_absolute_symlink'); + + // this one should still run, even if skipSymlinks is set, + // because it uses a junction. + var type = skipSymlinks ? 'junction' : 'dir'; + + console.log('using type=%s', type); + + var entry = tmpAbsDir + '/symlink', + expected = fixturesAbsDir + '/nested-index/one'; + [ + [entry, expected] + ].forEach(function(t) { + try {fs.unlinkSync(t[0]);} catch (e) {} + console.error('fs.symlinkSync(%j, %j, %j)', t[1], t[0], type); + fs.symlinkSync(t[1], t[0], type); + unlink.push(t[0]); + }); + var result = fs.realpathSync(entry); + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(expected)); + }); +} + +function test_deep_relative_file_symlink(callback) { + console.log('test_deep_relative_file_symlink'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + + var expected = path.join(common.fixturesDir, 'cycles', 'root.js'); + var linkData1 = '../../cycles/root.js'; + var linkPath1 = path.join(common.fixturesDir, + 'nested-index', 'one', 'symlink1.js'); + try {fs.unlinkSync(linkPath1);} catch (e) {} + fs.symlinkSync(linkData1, linkPath1, 'file'); + + var linkData2 = '../one/symlink1.js'; + var entry = path.join(common.fixturesDir, + 'nested-index', 'two', 'symlink1-b.js'); + try {fs.unlinkSync(entry);} catch (e) {} + fs.symlinkSync(linkData2, entry, 'file'); + unlink.push(linkPath1); + unlink.push(entry); + + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + }); +} + +function test_deep_relative_dir_symlink(callback) { + console.log('test_deep_relative_dir_symlink'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var expected = path.join(common.fixturesDir, 'cycles', 'folder'); + var linkData1b = '../../cycles/folder'; + var linkPath1b = path.join(common.fixturesDir, + 'nested-index', 'one', 'symlink1-dir'); + try {fs.unlinkSync(linkPath1b);} catch (e) {} + fs.symlinkSync(linkData1b, linkPath1b, 'dir'); + + var linkData2b = '../one/symlink1-dir'; + var entry = path.join(common.fixturesDir, + 'nested-index', 'two', 'symlink12-dir'); + try {fs.unlinkSync(entry);} catch (e) {} + fs.symlinkSync(linkData2b, entry, 'dir'); + unlink.push(linkPath1b); + unlink.push(entry); + + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + }); +} + +function test_cyclic_link_protection(callback) { + console.log('test_cyclic_link_protection'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var entry = common.tmpDir + '/cycles/realpath-3a'; + [ + [entry, '../cycles/realpath-3b'], + [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], + [common.tmpDir + '/cycles/realpath-3c', '../cycles/realpath-3a'] + ].forEach(function(t) { + try {fs.unlinkSync(t[0]);} catch (e) {} + fs.symlinkSync(t[1], t[0], 'dir'); + unlink.push(t[0]); + }); + assert.throws(function() { fs.realpathSync(entry); }); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.ok(err && true); + return true; + }); +} + +function test_cyclic_link_overprotection(callback) { + console.log('test_cyclic_link_overprotection'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + var cycles = common.tmpDir + '/cycles'; + var expected = fs.realpathSync(cycles); + var folder = cycles + '/folder'; + var link = folder + '/cycles'; + var testPath = cycles; + for (var i = 0; i < 10; i++) testPath += '/folder/cycles'; + try {fs.unlinkSync(link)} catch (ex) {} + fs.symlinkSync(cycles, link, 'dir'); + unlink.push(link); + assert.equal(fs.realpathSync(testPath), path.resolve(expected)); + asynctest(fs.realpath, [testPath], callback, function(er, res) { + assert.equal(res, path.resolve(expected)); + }); +} + +function test_relative_input_cwd(callback) { + console.log('test_relative_input_cwd'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + + // we need to get the relative path to the tmp dir from cwd. + // When the test runner is running it, that will be .../node/test + // but it's more common to run `./node test/.../`, so detect it here. + var entrydir = process.cwd(); + var entry = common.tmpDir.substr(entrydir.length + 1) + '/cycles/realpath-3a'; + var expected = common.tmpDir + '/cycles/root.js'; + [ + [entry, '../cycles/realpath-3b'], + [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], + [common.tmpDir + '/cycles/realpath-3c', 'root.js'] + ].forEach(function(t) { + var fn = t[0]; + console.error('fn=%j', fn); + try {fs.unlinkSync(fn);} catch (e) {} + var b = path.basename(t[1]); + var type = (b === 'root.js' ? 'file' : 'dir'); + console.log('fs.symlinkSync(%j, %j, %j)', t[1], fn, type); + fs.symlinkSync(t[1], fn, 'file'); + unlink.push(fn); + }); + + var origcwd = process.cwd(); + process.chdir(entrydir); + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + process.chdir(origcwd); + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + return true; + }); +} + +function test_deep_symlink_mix(callback) { + console.log('test_deep_symlink_mix'); + if (isWindows) { + // This one is a mix of files and directories, and it's quite tricky + // to get the file/dir links sorted out correctly. + console.log('skipping symlink test (no way to work on windows)'); + return runNextTest(); + } + + // todo: check to see that common.fixturesDir is not rooted in the + // same directory as our test symlink. + /* + /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo + /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 + /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 + /tmp/node-test-realpath-f2 + -> /node/test/fixtures/nested-index/one/realpath-c + /node/test/fixtures/nested-index/one/realpath-c + -> /node/test/fixtures/nested-index/two/realpath-c + /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js + /node/test/fixtures/cycles/root.js (hard) + */ + var entry = tmp('node-test-realpath-f1'); + try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {} + try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {} + fs.mkdirSync(tmp('node-test-realpath-d2'), 0700); + try { + [ + [entry, '../' + common.tmpDirName + '/node-test-realpath-d1/foo'], + [tmp('node-test-realpath-d1'), + '../' + common.tmpDirName + '/node-test-realpath-d2'], + [tmp('node-test-realpath-d2/foo'), '../node-test-realpath-f2'], + [tmp('node-test-realpath-f2'), fixturesAbsDir + + '/nested-index/one/realpath-c'], + [fixturesAbsDir + '/nested-index/one/realpath-c', fixturesAbsDir + + '/nested-index/two/realpath-c'], + [fixturesAbsDir + '/nested-index/two/realpath-c', + '../../../' + common.tmpDirName + '/cycles/root.js'] + ].forEach(function(t) { + //common.debug('setting up '+t[0]+' -> '+t[1]); + try { fs.unlinkSync(t[0]); } catch (e) {} + fs.symlinkSync(t[1], t[0]); + unlink.push(t[0]); + }); + } finally { + unlink.push(tmp('node-test-realpath-d2')); + } + var expected = tmpAbsDir + '/cycles/root.js'; + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + return true; + }); +} + +function test_non_symlinks(callback) { + console.log('test_non_symlinks'); + var entrydir = path.dirname(tmpAbsDir); + var entry = tmpAbsDir.substr(entrydir.length + 1) + '/cycles/root.js'; + var expected = tmpAbsDir + '/cycles/root.js'; + var origcwd = process.cwd(); + process.chdir(entrydir); + assert.equal(fs.realpathSync(entry), path.resolve(expected)); + asynctest(fs.realpath, [entry], callback, function(err, result) { + process.chdir(origcwd); + assert.equal(result, path.resolve(expected), + 'got ' + + common.inspect(result) + + ' expected ' + + common.inspect(path.resolve(expected))); + return true; + }); +} + +var upone = path.join(process.cwd(), '..'); +function test_escape_cwd(cb) { + console.log('test_escape_cwd'); + asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) { + assert.equal(upone, uponeActual, + 'realpath("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + }); +} +var uponeActual = fs.realpathSync('..'); +assert.equal(upone, uponeActual, + 'realpathSync("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + + +// going up with .. multiple times +// . +// `-- a/ +// |-- b/ +// | `-- e -> .. +// `-- d -> .. +// realpath(a/b/e/d/a/b/e/d/a) ==> a +function test_up_multiple(cb) { + console.error('test_up_multiple'); + if (skipSymlinks) { + console.log('skipping symlink test (no privs)'); + return runNextTest(); + } + function cleanup() { + ['a/b', + 'a' + ].forEach(function(folder) { + try {fs.rmdirSync(tmp(folder))} catch (ex) {} + }); + } + function setup() { + cleanup(); + } + setup(); + fs.mkdirSync(tmp('a'), 0755); + fs.mkdirSync(tmp('a/b'), 0755); + fs.symlinkSync('..', tmp('a/d'), 'dir'); + unlink.push(tmp('a/d')); + fs.symlinkSync('..', tmp('a/b/e'), 'dir'); + unlink.push(tmp('a/b/e')); + + var abedabed = tmp('abedabed'.split('').join('/')); + var abedabed_real = tmp(''); + + var abedabeda = tmp('abedabeda'.split('').join('/')); + var abedabeda_real = tmp('a'); + + assert.equal(fs.realpathSync(abedabeda), abedabeda_real); + assert.equal(fs.realpathSync(abedabed), abedabed_real); + fs.realpath(abedabeda, function (er, real) { + if (er) throw er; + assert.equal(abedabeda_real, real); + fs.realpath(abedabed, function (er, real) { + if (er) throw er; + assert.equal(abedabed_real, real); + cb(); + cleanup(); + }); + }); +} + + +// absolute symlinks with children. +// . +// `-- a/ +// |-- b/ +// | `-- c/ +// | `-- x.txt +// `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ +// realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' +function test_abs_with_kids(cb) { + console.log('test_abs_with_kids'); + + // this one should still run, even if skipSymlinks is set, + // because it uses a junction. + var type = skipSymlinks ? 'junction' : 'dir'; + + console.log('using type=%s', type); + + var root = tmpAbsDir + '/node-test-realpath-abs-kids'; + function cleanup() { + ['/a/b/c/x.txt', + '/a/link' + ].forEach(function(file) { + try {fs.unlinkSync(root + file)} catch (ex) {} + }); + ['/a/b/c', + '/a/b', + '/a', + '' + ].forEach(function(folder) { + try {fs.rmdirSync(root + folder)} catch (ex) {} + }); + } + function setup() { + cleanup(); + ['', + '/a', + '/a/b', + '/a/b/c' + ].forEach(function(folder) { + console.log('mkdir ' + root + folder); + fs.mkdirSync(root + folder, 0700); + }); + fs.writeFileSync(root + '/a/b/c/x.txt', 'foo'); + fs.symlinkSync(root + '/a/b', root + '/a/link', type); + } + setup(); + var linkPath = root + '/a/link/c/x.txt'; + var expectPath = root + '/a/b/c/x.txt'; + var actual = fs.realpathSync(linkPath); + // console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); + assert.equal(actual, path.resolve(expectPath)); + asynctest(fs.realpath, [linkPath], cb, function(er, actual) { + // console.log({link:linkPath,expect:expectPath,actual:actual},'async'); + assert.equal(actual, path.resolve(expectPath)); + cleanup(); + }); +} + +function test_lying_cache_liar(cb) { + var n = 2; + + // this should not require *any* stat calls, since everything + // checked by realpath will be found in the cache. + console.log('test_lying_cache_liar'); + var cache = { '/foo/bar/baz/bluff' : '/foo/bar/bluff', + '/1/2/3/4/5/6/7' : '/1', + '/a' : '/a', + '/a/b' : '/a/b', + '/a/b/c' : '/a/b', + '/a/b/d' : '/a/b/d' }; + if (isWindows) { + var wc = {}; + Object.keys(cache).forEach(function(k) { + wc[ path.resolve(k) ] = path.resolve(cache[k]); + }); + cache = wc; + } + + var bluff = path.resolve('/foo/bar/baz/bluff'); + var rps = fs.realpathSync(bluff, cache); + assert.equal(cache[bluff], rps); + var nums = path.resolve('/1/2/3/4/5/6/7'); + var called = false; // no sync cb calling! + fs.realpath(nums, cache, function(er, rp) { + called = true; + assert.equal(cache[nums], rp); + if (--n === 0) cb(); + }); + assert(called === false); + + var test = path.resolve('/a/b/c/d'), + expect = path.resolve('/a/b/d'); + var actual = fs.realpathSync(test, cache); + assert.equal(expect, actual); + fs.realpath(test, cache, function(er, actual) { + assert.equal(expect, actual); + if (--n === 0) cb(); + }); +} + +// ---------------------------------------------------------------------------- + +var tests = [ + test_simple_error_callback, + test_simple_relative_symlink, + test_simple_absolute_symlink, + test_deep_relative_file_symlink, + test_deep_relative_dir_symlink, + test_cyclic_link_protection, + test_cyclic_link_overprotection, + test_relative_input_cwd, + test_deep_symlink_mix, + test_non_symlinks, + test_escape_cwd, + test_abs_with_kids, + test_lying_cache_liar, + test_up_multiple +]; +var numtests = tests.length; +var testsRun = 0; +function runNextTest(err) { + if (err) throw err; + var test = tests.shift(); + if (!test) { + return console.log(numtests + + ' subtests completed OK for fs.realpath'); + } + testsRun++; + test(runNextTest); +} + + +assert.equal(root, fs.realpathSync('/')); +fs.realpath('/', function(err, result) { + assert.equal(null, err); + assert.equal(root, result); +}); + + +function runTest() { + var tmpDirs = ['cycles', 'cycles/folder']; + tmpDirs.forEach(function(t) { + t = tmp(t); + var s; + try { s = fs.statSync(t); } catch (ex) {} + if (s) return; + fs.mkdirSync(t, 0700); + }); + fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); + console.error('start tests'); + runNextTest(); +} + + +process.on('exit', function() { + assert.equal(numtests, testsRun); + unlink.forEach(function(path) { try {fs.unlinkSync(path);} catch (e) {} }); + assert.equal(async_completed, async_expected); +}); diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js new file mode 100644 index 000000000..e16f56bdc --- /dev/null +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var fs = require('fs'); +var assert = require('assert'); +var join = require('path').join; + +var filename = join(common.tmpDir, 'out.txt'); + +try { + fs.unlinkSync(filename); +} catch (e) { + // might not exist, that's okay. +} + +var fd = fs.openSync(filename, 'w'); + +var line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; + +var N = 10240, complete = 0; +for (var i = 0; i < N; i++) { + // Create a new buffer for each write. Before the write is actually + // executed by the thread pool, the buffer will be collected. + var buffer = new Buffer(line); + fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { + complete++; + if (complete === N) { + fs.closeSync(fd); + var s = fs.createReadStream(filename); + s.on('data', testBuffer); + } + }); +} + +var bytesChecked = 0; + +function testBuffer(b) { + for (var i = 0; i < b.length; i++) { + bytesChecked++; + if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) { + throw new Error('invalid char ' + i + ',' + b[i]); + } + } +} + +process.on('exit', function() { + // Probably some of the writes are going to overlap, so we can't assume + // that we get (N * line.length). Let's just make sure we've checked a + // few... + assert.ok(bytesChecked > 1000); +}); + diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js new file mode 100644 index 000000000..8c5a9c64c --- /dev/null +++ b/test/parallel/test-fs-stat.js @@ -0,0 +1,128 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var got_error = false; +var success_count = 0; + +fs.stat('.', function(err, stats) { + if (err) { + got_error = true; + } else { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + } + assert(this === global); +}); + +fs.stat('.', function(err, stats) { + assert.ok(stats.hasOwnProperty('blksize')); + assert.ok(stats.hasOwnProperty('blocks')); +}); + +fs.lstat('.', function(err, stats) { + if (err) { + got_error = true; + } else { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + } + assert(this === global); +}); + +// fstat +fs.open('.', 'r', undefined, function(err, fd) { + assert.ok(!err); + assert.ok(fd); + + fs.fstat(fd, function(err, stats) { + if (err) { + got_error = true; + } else { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + fs.close(fd); + } + assert(this === global); + }); + + assert(this === global); +}); + +// fstatSync +fs.open('.', 'r', undefined, function(err, fd) { + var stats; + try { + stats = fs.fstatSync(fd); + } catch (err) { + got_error = true; + } + if (stats) { + console.dir(stats); + assert.ok(stats.mtime instanceof Date); + success_count++; + } + fs.close(fd); +}); + +console.log('stating: ' + __filename); +fs.stat(__filename, function(err, s) { + if (err) { + got_error = true; + } else { + console.dir(s); + success_count++; + + console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); + assert.equal(false, s.isDirectory()); + + console.log('isFile: ' + JSON.stringify(s.isFile())); + assert.equal(true, s.isFile()); + + console.log('isSocket: ' + JSON.stringify(s.isSocket())); + assert.equal(false, s.isSocket()); + + console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); + assert.equal(false, s.isBlockDevice()); + + console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); + assert.equal(false, s.isCharacterDevice()); + + console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); + assert.equal(false, s.isFIFO()); + + console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); + assert.equal(false, s.isSymbolicLink()); + + assert.ok(s.mtime instanceof Date); + } +}); + +process.on('exit', function() { + assert.equal(5, success_count); + assert.equal(false, got_error); +}); + diff --git a/test/parallel/test-fs-stream-double-close.js b/test/parallel/test-fs-stream-double-close.js new file mode 100644 index 000000000..89386b6e6 --- /dev/null +++ b/test/parallel/test-fs-stream-double-close.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +test1(fs.createReadStream(__filename)); +test2(fs.createReadStream(__filename)); +test3(fs.createReadStream(__filename)); + +test1(fs.createWriteStream(common.tmpDir + '/dummy1')); +test2(fs.createWriteStream(common.tmpDir + '/dummy2')); +test3(fs.createWriteStream(common.tmpDir + '/dummy3')); + +function test1(stream) { + stream.destroy(); + stream.destroy(); +} + +function test2(stream) { + stream.destroy(); + stream.on('open', function(fd) { + stream.destroy(); + open_cb_called++; + }); + process.on('exit', function() { + assert.equal(open_cb_called, 1); + }); + var open_cb_called = 0; +} + +function test3(stream) { + stream.on('open', function(fd) { + stream.destroy(); + stream.destroy(); + open_cb_called++; + }); + process.on('exit', function() { + assert.equal(open_cb_called, 1); + }); + var open_cb_called = 0; +} diff --git a/test/parallel/test-fs-symlink-dir-junction-relative.js b/test/parallel/test-fs-symlink-dir-junction-relative.js new file mode 100644 index 000000000..c598d2e92 --- /dev/null +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Test creating and resolving relative junction or symbolic link + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var completed = 0; +var expected_tests = 2; + +var linkPath1 = path.join(common.tmpDir, 'junction1'); +var linkPath2 = path.join(common.tmpDir, 'junction2'); +var linkTarget = path.join(common.fixturesDir); +var linkData = '../fixtures'; + +// Prepare. +try { fs.mkdirSync(common.tmpDir); } catch (e) {} +try { fs.unlinkSync(linkPath1); } catch (e) {} +try { fs.unlinkSync(linkPath2); } catch (e) {} + +// Test fs.symlink() +fs.symlink(linkData, linkPath1, 'junction', function(err) { + if (err) throw err; + verifyLink(linkPath1); +}); + +// Test fs.symlinkSync() +fs.symlinkSync(linkData, linkPath2, 'junction'); +verifyLink(linkPath2); + +function verifyLink(linkPath) { + var stats = fs.lstatSync(linkPath); + assert.ok(stats.isSymbolicLink()); + + var data1 = fs.readFileSync(linkPath + '/x.txt', 'ascii'); + var data2 = fs.readFileSync(linkTarget + '/x.txt', 'ascii'); + assert.strictEqual(data1, data2); + + // Clean up. + fs.unlinkSync(linkPath); + + completed++; +} + +process.on('exit', function() { + assert.equal(completed, expected_tests); +}); + diff --git a/test/parallel/test-fs-symlink-dir-junction.js b/test/parallel/test-fs-symlink-dir-junction.js new file mode 100644 index 000000000..c675b920e --- /dev/null +++ b/test/parallel/test-fs-symlink-dir-junction.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var completed = 0; +var expected_tests = 4; + +// test creating and reading symbolic link +var linkData = path.join(common.fixturesDir, 'cycles/'); +var linkPath = path.join(common.tmpDir, 'cycles_link'); + +// Delete previously created link +try { + fs.unlinkSync(linkPath); +} catch (e) {} + +console.log('linkData: ' + linkData); +console.log('linkPath: ' + linkPath); + +fs.symlink(linkData, linkPath, 'junction', function(err) { + if (err) throw err; + completed++; + + fs.lstat(linkPath, function(err, stats) { + if (err) throw err; + assert.ok(stats.isSymbolicLink()); + completed++; + + fs.readlink(linkPath, function(err, destination) { + if (err) throw err; + assert.equal(destination, linkData); + completed++; + + fs.unlink(linkPath, function(err) { + if (err) throw err; + assert(!fs.existsSync(linkPath)); + assert(fs.existsSync(linkData)); + completed++; + }); + }); + }); +}); + +process.on('exit', function() { + assert.equal(completed, expected_tests); +}); + diff --git a/test/parallel/test-fs-symlink.js b/test/parallel/test-fs-symlink.js new file mode 100644 index 000000000..6b23b1e1c --- /dev/null +++ b/test/parallel/test-fs-symlink.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var exec = require('child_process').exec; +var completed = 0; +var expected_tests = 2; + +var is_windows = process.platform === 'win32'; + +var runtest = function(skip_symlinks) { + if (!skip_symlinks) { + // test creating and reading symbolic link + var linkData = path.join(common.fixturesDir, '/cycles/root.js'); + var linkPath = path.join(common.tmpDir, 'symlink1.js'); + + // Delete previously created link + try { + fs.unlinkSync(linkPath); + } catch (e) {} + + fs.symlink(linkData, linkPath, function(err) { + if (err) throw err; + console.log('symlink done'); + // todo: fs.lstat? + fs.readlink(linkPath, function(err, destination) { + if (err) throw err; + assert.equal(destination, linkData); + completed++; + }); + }); + } + + // test creating and reading hard link + var srcPath = path.join(common.fixturesDir, 'cycles', 'root.js'); + var dstPath = path.join(common.tmpDir, 'link1.js'); + + // Delete previously created link + try { + fs.unlinkSync(dstPath); + } catch (e) {} + + fs.link(srcPath, dstPath, function(err) { + if (err) throw err; + console.log('hard link done'); + var srcContent = fs.readFileSync(srcPath, 'utf8'); + var dstContent = fs.readFileSync(dstPath, 'utf8'); + assert.equal(srcContent, dstContent); + completed++; + }); +}; + +if (is_windows) { + // On Windows, creating symlinks requires admin privileges. + // We'll only try to run symlink test if we have enough privileges. + exec('whoami /priv', function(err, o) { + if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { + expected_tests = 1; + runtest(true); + } else { + runtest(false); + } + }); +} else { + runtest(false); +} + +process.on('exit', function() { + assert.equal(completed, expected_tests); +}); + diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js new file mode 100644 index 000000000..fe932c7df --- /dev/null +++ b/test/parallel/test-fs-sync-fd-leak.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +// ensure that (read|write|append)FileSync() closes the file descriptor +fs.openSync = function() { + return 42; +}; +fs.closeSync = function(fd) { + assert.equal(fd, 42); + close_called++; +}; +fs.readSync = function() { + throw new Error('BAM'); +}; +fs.writeSync = function() { + throw new Error('BAM'); +}; + +fs.fstatSync = function() { + throw new Error('BAM'); +}; + +ensureThrows(function() { + fs.readFileSync('dummy'); +}); +ensureThrows(function() { + fs.writeFileSync('dummy', 'xxx'); +}); +ensureThrows(function() { + fs.appendFileSync('dummy', 'xxx'); +}); + +var close_called = 0; +function ensureThrows(cb) { + var got_exception = false; + + close_called = 0; + try { + cb(); + } catch (e) { + assert.equal(e.message, 'BAM'); + got_exception = true; + } + + assert.equal(close_called, 1); + assert.equal(got_exception, true); +} diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js new file mode 100644 index 000000000..472afdcab --- /dev/null +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var filename = common.tmpDir + '/truncate-file.txt'; + +// Synchronous test. +(function() { + fs.writeFileSync(filename, '0123456789'); + assert.equal(fs.readFileSync(filename).toString(), '0123456789'); + fs.truncateSync(filename, 5); + assert.equal(fs.readFileSync(filename).toString(), '01234'); +})(); + +// Asynchronous test. +(function() { + fs.writeFileSync(filename, '0123456789'); + assert.equal(fs.readFileSync(filename).toString(), '0123456789'); + fs.truncate(filename, 5, common.mustCall(function(err) { + if (err) throw err; + assert.equal(fs.readFileSync(filename).toString(), '01234'); + })); +})(); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js new file mode 100644 index 000000000..09476b2ad --- /dev/null +++ b/test/parallel/test-fs-truncate.js @@ -0,0 +1,135 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var tmp = common.tmpDir; +var filename = path.resolve(tmp, 'truncate-file.txt'); +var data = new Buffer(1024 * 16); +data.fill('x'); + +var stat; + +// truncateSync +fs.writeFileSync(filename, data); +stat = fs.statSync(filename); +assert.equal(stat.size, 1024 * 16); + +fs.truncateSync(filename, 1024); +stat = fs.statSync(filename); +assert.equal(stat.size, 1024); + +fs.truncateSync(filename); +stat = fs.statSync(filename); +assert.equal(stat.size, 0); + +// ftruncateSync +fs.writeFileSync(filename, data); +var fd = fs.openSync(filename, 'r+'); + +stat = fs.statSync(filename); +assert.equal(stat.size, 1024 * 16); + +fs.ftruncateSync(fd, 1024); +stat = fs.statSync(filename); +assert.equal(stat.size, 1024); + +fs.ftruncateSync(fd); +stat = fs.statSync(filename); +assert.equal(stat.size, 0); + +fs.closeSync(fd); + +// async tests +var success = 0; +testTruncate(function(er) { + if (er) throw er; + success++; + testFtruncate(function(er) { + if (er) throw er; + success++; + }); +}); + +process.on('exit', function() { + assert.equal(success, 2); + console.log('ok'); +}); + +function testTruncate(cb) { + fs.writeFile(filename, data, function(er) { + if (er) return cb(er); + fs.stat(filename, function(er, stat) { + if (er) return cb(er); + assert.equal(stat.size, 1024 * 16); + + fs.truncate(filename, 1024, function(er) { + if (er) return cb(er); + fs.stat(filename, function(er, stat) { + if (er) return cb(er); + assert.equal(stat.size, 1024); + + fs.truncate(filename, function(er) { + if (er) return cb(er); + fs.stat(filename, function(er, stat) { + if (er) return cb(er); + assert.equal(stat.size, 0); + cb(); + }); + }); + }); + }); + }); + }); +} + + +function testFtruncate(cb) { + fs.writeFile(filename, data, function(er) { + if (er) return cb(er); + fs.stat(filename, function(er, stat) { + if (er) return cb(er); + assert.equal(stat.size, 1024 * 16); + + fs.open(filename, 'w', function(er, fd) { + if (er) return cb(er); + fs.ftruncate(fd, 1024, function(er) { + if (er) return cb(er); + fs.stat(filename, function(er, stat) { + if (er) return cb(er); + assert.equal(stat.size, 1024); + + fs.ftruncate(fd, function(er) { + if (er) return cb(er); + fs.stat(filename, function(er, stat) { + if (er) return cb(er); + assert.equal(stat.size, 0); + fs.close(fd, cb); + }); + }); + }); + }); + }); + }); + }); +} diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js new file mode 100644 index 000000000..eae80238b --- /dev/null +++ b/test/parallel/test-fs-utimes.js @@ -0,0 +1,160 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var fs = require('fs'); + +var is_windows = process.platform === 'win32'; + +var tests_ok = 0; +var tests_run = 0; + +function stat_resource(resource) { + if (typeof resource == 'string') { + return fs.statSync(resource); + } else { + // ensure mtime has been written to disk + fs.fsyncSync(resource); + return fs.fstatSync(resource); + } +} + +function check_mtime(resource, mtime) { + var mtime = fs._toUnixTimestamp(mtime); + var stats = stat_resource(resource); + var real_mtime = fs._toUnixTimestamp(stats.mtime); + // check up to single-second precision + // sub-second precision is OS and fs dependant + return Math.floor(mtime) == Math.floor(real_mtime); +} + +function expect_errno(syscall, resource, err, errno) { + if (err && (err.code === errno || err.code === 'ENOSYS')) { + tests_ok++; + } else { + console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); + } +} + +function expect_ok(syscall, resource, err, atime, mtime) { + if (!err && check_mtime(resource, mtime) || + err && err.code === 'ENOSYS') { + tests_ok++; + } else { + console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); + } +} + +// the tests assume that __filename belongs to the user running the tests +// this should be a fairly safe assumption; testing against a temp file +// would be even better though (node doesn't have such functionality yet) +function runTest(atime, mtime, callback) { + + var fd, err; + // + // test synchronized code paths, these functions throw on failure + // + function syncTests() { + fs.utimesSync(__filename, atime, mtime); + expect_ok('utimesSync', __filename, undefined, atime, mtime); + tests_run++; + + // some systems don't have futimes + // if there's an error, it should be ENOSYS + try { + tests_run++; + fs.futimesSync(fd, atime, mtime); + expect_ok('futimesSync', fd, undefined, atime, mtime); + } catch (ex) { + expect_errno('futimesSync', fd, ex, 'ENOSYS'); + } + + var err; + err = undefined; + try { + fs.utimesSync('foobarbaz', atime, mtime); + } catch (ex) { + err = ex; + } + expect_errno('utimesSync', 'foobarbaz', err, 'ENOENT'); + tests_run++; + + err = undefined; + try { + fs.futimesSync(-1, atime, mtime); + } catch (ex) { + err = ex; + } + expect_errno('futimesSync', -1, err, 'EBADF'); + tests_run++; + } + + // + // test async code paths + // + fs.utimes(__filename, atime, mtime, function(err) { + expect_ok('utimes', __filename, err, atime, mtime); + + fs.utimes('foobarbaz', atime, mtime, function(err) { + expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); + + // don't close this fd + if (is_windows) { + fd = fs.openSync(__filename, 'r+'); + } else { + fd = fs.openSync(__filename, 'r'); + } + + fs.futimes(fd, atime, mtime, function(err) { + expect_ok('futimes', fd, err, atime, mtime); + + fs.futimes(-1, atime, mtime, function(err) { + expect_errno('futimes', -1, err, 'EBADF'); + syncTests(); + callback(); + }); + tests_run++; + }); + tests_run++; + }); + tests_run++; + }); + tests_run++; +} + +var stats = fs.statSync(__filename); + +runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { + runTest(new Date(), new Date(), function() { + runTest(123456.789, 123456.789, function() { + runTest(stats.mtime, stats.mtime, function() { + // done + }); + }); + }); +}); + +process.on('exit', function() { + console.log('Tests run / ok:', tests_run, '/', tests_ok); + assert.equal(tests_ok, tests_run); +}); diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js new file mode 100644 index 000000000..46013bd87 --- /dev/null +++ b/test/parallel/test-fs-write-buffer.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'), + Buffer = require('buffer').Buffer, + fs = require('fs'), + filename = path.join(common.tmpDir, 'write.txt'), + expected = new Buffer('hello'), + openCalled = 0, + writeCalled = 0; + + +fs.open(filename, 'w', 0644, function(err, fd) { + openCalled++; + if (err) throw err; + + fs.write(fd, expected, 0, expected.length, null, function(err, written) { + writeCalled++; + if (err) throw err; + + assert.equal(expected.length, written); + fs.closeSync(fd); + + var found = fs.readFileSync(filename, 'utf8'); + assert.deepEqual(expected.toString(), found); + fs.unlinkSync(filename); + }); +}); + +process.on('exit', function() { + assert.equal(1, openCalled); + assert.equal(1, writeCalled); +}); + diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js new file mode 100644 index 000000000..dfe7cf5f3 --- /dev/null +++ b/test/parallel/test-fs-write-file-buffer.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var join = require('path').join; +var util = require('util'); +var fs = require('fs'); + +var data = [ + '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', + 'Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/', + '2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e', + 'Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAQABADASIAAhEBAxEB/8QA', + 'HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF', + 'BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK', + 'FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1', + 'dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG', + 'x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEB', + 'AQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC', + 'AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRom', + 'JygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE', + 'hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU', + '1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDhfBUFl/wk', + 'OmPqKJJZw3aiZFBw4z93jnkkc9u9dj8XLfSI/EBt7DTo7ea2Ox5YXVo5FC7g', + 'Tjq24nJPXNVtO0KATRvNHCIg3zoWJWQHqp+o4pun+EtJ0zxBq8mnLJa2d1L5', + '0NvnKRjJBUE5PAx3NYxxUY0pRtvYHSc5Ka2X9d7H/9k=']; + +data = data.join('\n'); + +var buf = new Buffer(data, 'base64'); +fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); + +util.log('Done!'); diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js new file mode 100644 index 000000000..3e723425a --- /dev/null +++ b/test/parallel/test-fs-write-file-sync.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var isWindows = process.platform === 'win32'; +var openCount = 0; +var mode; +var content; + +// Need to hijack fs.open/close to make sure that things +// get closed once they're opened. +fs._openSync = fs.openSync; +fs.openSync = openSync; +fs._closeSync = fs.closeSync; +fs.closeSync = closeSync; + +// Reset the umask for testing +var mask = process.umask(0000); + +// On Windows chmod is only able to manipulate read-only bit. Test if creating +// the file in read-only mode works. +if (isWindows) { + mode = 0444; +} else { + mode = 0755; +} + +// Test writeFileSync +var file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); +removeFile(file1); + +fs.writeFileSync(file1, '123', {mode: mode}); + +content = fs.readFileSync(file1, {encoding: 'utf8'}); +assert.equal('123', content); + +assert.equal(mode, fs.statSync(file1).mode & 0777); + +removeFile(file1); + +// Test appendFileSync +var file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); +removeFile(file2); + +fs.appendFileSync(file2, 'abc', {mode: mode}); + +content = fs.readFileSync(file2, {encoding: 'utf8'}); +assert.equal('abc', content); + +assert.equal(mode, fs.statSync(file2).mode & mode); + +removeFile(file2); + +// Verify that all opened files were closed. +assert.equal(0, openCount); + +// Removes a file if it exists. +function removeFile(file) { + try { + if (isWindows) + fs.chmodSync(file, 0666); + fs.unlinkSync(file); + } catch (err) { + if (err && err.code !== 'ENOENT') + throw err; + } +} + +function openSync() { + openCount++; + return fs._openSync.apply(fs, arguments); +} + +function closeSync() { + openCount--; + return fs._closeSync.apply(fs, arguments); +} diff --git a/test/parallel/test-fs-write-file.js b/test/parallel/test-fs-write-file.js new file mode 100644 index 000000000..b70ea444c --- /dev/null +++ b/test/parallel/test-fs-write-file.js @@ -0,0 +1,108 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var join = require('path').join; + +var filename = join(common.tmpDir, 'test.txt'); + +common.error('writing to ' + filename); + +var n = 220; +var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + + '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + + '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + + '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; + +var ncallbacks = 0; + +fs.writeFile(filename, s, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('file written'); + + fs.readFile(filename, function(e, buffer) { + if (e) throw e; + common.error('file read'); + ncallbacks++; + assert.equal(Buffer.byteLength(s), buffer.length); + }); +}); + +// test that writeFile accepts buffers +var filename2 = join(common.tmpDir, 'test2.txt'); +var buf = new Buffer(s, 'utf8'); +common.error('writing to ' + filename2); + +fs.writeFile(filename2, buf, function(e) { + if (e) throw e; + + ncallbacks++; + common.error('file2 written'); + + fs.readFile(filename2, function(e, buffer) { + if (e) throw e; + common.error('file2 read'); + ncallbacks++; + assert.equal(buf.length, buffer.length); + }); +}); + +// test that writeFile accepts numbers. +var filename3 = join(common.tmpDir, 'test3.txt'); +common.error('writing to ' + filename3); + +var m = 0600; +fs.writeFile(filename3, n, { mode: m }, function(e) { + if (e) throw e; + + // windows permissions aren't unix + if (process.platform !== 'win32') { + var st = fs.statSync(filename3); + assert.equal(st.mode & 0700, m); + } + + ncallbacks++; + common.error('file3 written'); + + fs.readFile(filename3, function(e, buffer) { + if (e) throw e; + common.error('file3 read'); + ncallbacks++; + assert.equal(Buffer.byteLength('' + n), buffer.length); + }); +}); + + +process.on('exit', function() { + common.error('done'); + assert.equal(6, ncallbacks); + + fs.unlinkSync(filename); + fs.unlinkSync(filename2); + fs.unlinkSync(filename3); +}); diff --git a/test/parallel/test-fs-write-stream-change-open.js b/test/parallel/test-fs-write-stream-change-open.js new file mode 100644 index 000000000..d025e8da3 --- /dev/null +++ b/test/parallel/test-fs-write-stream-change-open.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'); + +var file = path.join(common.tmpDir, 'write.txt'); + +var stream = fs.WriteStream(file), + _fs_close = fs.close, + _fs_open = fs.open; + +// change the fs.open with an identical function after the WriteStream +// has pushed it onto its internal action queue, but before it's +// returned. This simulates AOP-style extension of the fs lib. +fs.open = function() { + return _fs_open.apply(fs, arguments); +}; + +fs.close = function(fd) { + assert.ok(fd, 'fs.close must not be called with an undefined fd.'); + fs.close = _fs_close; + fs.open = _fs_open; +} + +stream.write('foo'); +stream.end(); + +process.on('exit', function() { + assert.equal(fs.open, _fs_open); +}); diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js new file mode 100644 index 000000000..7bbc5d68e --- /dev/null +++ b/test/parallel/test-fs-write-stream-end.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +(function() { + var file = path.join(common.tmpDir, 'write-end-test0.txt'); + var stream = fs.createWriteStream(file); + stream.end(); + stream.on('close', common.mustCall(function() { })); +})(); + +(function() { + var file = path.join(common.tmpDir, 'write-end-test1.txt'); + var stream = fs.createWriteStream(file); + stream.end('a\n', 'utf8'); + stream.on('close', common.mustCall(function() { + var content = fs.readFileSync(file, 'utf8'); + assert.equal(content, 'a\n'); + })); +})(); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js new file mode 100644 index 000000000..53ef4e34e --- /dev/null +++ b/test/parallel/test-fs-write-stream-err.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); + +var stream = fs.createWriteStream(common.tmpDir + '/out', { + highWaterMark: 10 +}); +var err = new Error('BAM'); + +var write = fs.write; +var writeCalls = 0; +fs.write = function() { + switch (writeCalls++) { + case 0: + console.error('first write'); + // first time is ok. + return write.apply(fs, arguments); + case 1: + // then it breaks + console.error('second write'); + var cb = arguments[arguments.length - 1]; + return process.nextTick(function() { + cb(err); + }); + default: + // and should not be called again! + throw new Error('BOOM!'); + } +}; + +fs.close = common.mustCall(function(fd_, cb) { + console.error('fs.close', fd_, stream.fd); + assert.equal(fd_, stream.fd); + process.nextTick(cb); +}); + +stream.on('error', common.mustCall(function(err_) { + console.error('error handler'); + assert.equal(stream.fd, null); + assert.equal(err_, err); +})); + + +stream.write(new Buffer(256), function() { + console.error('first cb'); + stream.write(new Buffer(256), common.mustCall(function(err_) { + console.error('second cb'); + assert.equal(err_, err); + })); +}); diff --git a/test/parallel/test-fs-write-stream.js b/test/parallel/test-fs-write-stream.js new file mode 100644 index 000000000..da75e26f8 --- /dev/null +++ b/test/parallel/test-fs-write-stream.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'), + fs = require('fs'); + +var file = path.join(common.tmpDir, 'write.txt'); + +(function() { + var stream = fs.WriteStream(file), + _fs_close = fs.close; + + fs.close = function(fd) { + assert.ok(fd, 'fs.close must not be called without an undefined fd.'); + fs.close = _fs_close; + } + stream.destroy(); +})(); + +(function() { + var stream = fs.createWriteStream(file); + + stream.on('drain', function() { + assert.fail('\'drain\' event must not be emitted before ' + + 'stream.write() has been called at least once.'); + }); + stream.destroy(); +})(); + diff --git a/test/parallel/test-fs-write-sync.js b/test/parallel/test-fs-write-sync.js new file mode 100644 index 000000000..c3dbfe3ba --- /dev/null +++ b/test/parallel/test-fs-write-sync.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); +var fn = path.join(common.tmpDir, 'write.txt'); + + +var foo = 'foo'; +var fd = fs.openSync(fn, 'w'); + +var written = fs.writeSync(fd, ''); +assert.strictEqual(0, written); + +fs.writeSync(fd, foo); + +var bar = 'bár'; +written = fs.writeSync(fd, new Buffer(bar), 0, Buffer.byteLength(bar)); +assert.ok(written > 3); +fs.closeSync(fd); + +assert.equal(fs.readFileSync(fn), 'foobár'); diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js new file mode 100644 index 000000000..3d7a357a9 --- /dev/null +++ b/test/parallel/test-fs-write.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var Buffer = require('buffer').Buffer; +var fs = require('fs'); +var fn = path.join(common.tmpDir, 'write.txt'); +var fn2 = path.join(common.tmpDir, 'write2.txt'); +var expected = 'ümlaut.'; +var constants = require('constants'); +var found, found2; + +fs.open(fn, 'w', 0644, function(err, fd) { + if (err) throw err; + console.log('open done'); + fs.write(fd, '', 0, 'utf8', function(err, written) { + assert.equal(0, written); + }); + fs.write(fd, expected, 0, 'utf8', function(err, written) { + console.log('write done'); + if (err) throw err; + assert.equal(Buffer.byteLength(expected), written); + fs.closeSync(fd); + found = fs.readFileSync(fn, 'utf8'); + console.log('expected: "%s"', expected); + console.log('found: "%s"', found); + fs.unlinkSync(fn); + }); +}); + + +fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0644, + function(err, fd) { + if (err) throw err; + console.log('open done'); + fs.write(fd, '', 0, 'utf8', function(err, written) { + assert.equal(0, written); + }); + fs.write(fd, expected, 0, 'utf8', function(err, written) { + console.log('write done'); + if (err) throw err; + assert.equal(Buffer.byteLength(expected), written); + fs.closeSync(fd); + found2 = fs.readFileSync(fn2, 'utf8'); + console.log('expected: "%s"', expected); + console.log('found: "%s"', found2); + fs.unlinkSync(fn2); + }); + }); + + +process.on('exit', function() { + assert.equal(expected, found); + assert.equal(expected, found2); +}); + diff --git a/test/parallel/test-global.js b/test/parallel/test-global.js new file mode 100644 index 000000000..4cc9799ba --- /dev/null +++ b/test/parallel/test-global.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.globalCheck = false; + +baseFoo = 'foo'; +global.baseBar = 'bar'; + +assert.equal('foo', global.baseFoo, 'x -> global.x in base level not working'); + +assert.equal('bar', baseBar, 'global.x -> x in base level not working'); + +var module = require('../fixtures/global/plain'), + fooBar = module.fooBar; + +assert.equal('foo', fooBar.foo, 'x -> global.x in sub level not working'); + +assert.equal('bar', fooBar.bar, 'global.x -> x in sub level not working'); diff --git a/test/parallel/test-handle-wrap-close-abort.js b/test/parallel/test-handle-wrap-close-abort.js new file mode 100644 index 000000000..287c38b23 --- /dev/null +++ b/test/parallel/test-handle-wrap-close-abort.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +process.on('uncaughtException', function() { }); + +setTimeout(function() { + process.nextTick(function() { + var c = setInterval(function() { + clearInterval(c); + throw new Error('setInterval'); + }); + }); + setTimeout(function() { + throw new Error('setTimeout'); + }); +}); diff --git a/test/parallel/test-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js new file mode 100644 index 000000000..851409d28 --- /dev/null +++ b/test/parallel/test-http-1.0-keep-alive.js @@ -0,0 +1,152 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +// Check that our HTTP server correctly handles HTTP/1.0 keep-alive requests. +check([{ + name: 'keep-alive, no TE header', + requests: [{ + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}, { + name: 'keep-alive, with TE: chunked', + requests: [{ + expectClose: false, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + 'TE: chunked\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}, { + name: 'keep-alive, with Transfer-Encoding: chunked', + requests: [{ + expectClose: false, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive', + 'Transfer-Encoding': 'chunked'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}, { + name: 'keep-alive, with Content-Length', + requests: [{ + expectClose: false, + data: 'POST / HTTP/1.0\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + }, { + expectClose: true, + data: 'POST / HTTP/1.0\r\n' + + '\r\n' + }], + responses: [{ + headers: {'Connection': 'keep-alive', + 'Content-Length': '2'}, + chunks: ['OK'] + }, { + chunks: [] + }] +}]); + +function check(tests) { + var test = tests[0]; + if (test) http.createServer(server).listen(common.PORT, '127.0.0.1', client); + var current = 0; + + function next() { + check(tests.slice(1)); + } + + function server(req, res) { + if (current + 1 === test.responses.length) this.close(); + var ctx = test.responses[current]; + console.error('< SERVER SENDING RESPONSE', ctx); + res.writeHead(200, ctx.headers); + ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk) }); + res.end(ctx.chunks[ctx.chunks.length - 1]); + } + + function client() { + if (current === test.requests.length) return next(); + var conn = net.createConnection(common.PORT, '127.0.0.1', connected); + + function connected() { + var ctx = test.requests[current]; + console.error(' > CLIENT SENDING REQUEST', ctx); + conn.setEncoding('utf8'); + conn.write(ctx.data); + + function onclose() { + console.error(' > CLIENT CLOSE'); + if (!ctx.expectClose) throw new Error('unexpected close'); + client(); + } + conn.on('close', onclose); + + function ondata(s) { + console.error(' > CLIENT ONDATA %j %j', s.length, s.toString()); + current++; + if (ctx.expectClose) return; + conn.removeListener('close', onclose); + conn.removeListener('data', ondata);; + connected(); + } + conn.on('data', ondata); + } + } +} diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js new file mode 100644 index 000000000..f5f3aef0a --- /dev/null +++ b/test/parallel/test-http-1.0.js @@ -0,0 +1,181 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +var body = 'hello world\n'; + +var common_port = common.PORT; + +function test(handler, request_generator, response_validator) { + var port = common_port++; + var server = http.createServer(handler); + + var client_got_eof = false; + var server_response = { + data: '', + chunks: [] + }; + + function cleanup() { + server.close(); + response_validator(server_response, client_got_eof, true); + } + var timer = setTimeout(cleanup, 1000); + process.on('exit', cleanup); + + server.listen(port); + server.on('listening', function() { + var c = net.createConnection(port); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write(request_generator()); + }); + + c.on('data', function(chunk) { + server_response.data += chunk; + server_response.chunks.push(chunk); + }); + + c.on('end', function() { + client_got_eof = true; + c.end(); + server.close(); + clearTimeout(timer); + process.removeListener('exit', cleanup); + response_validator(server_response, client_got_eof, false); + }); + }); +} + +(function() { + function handler(req, res) { + assert.equal('1.0', req.httpVersion); + assert.equal(1, req.httpVersionMajor); + assert.equal(0, req.httpVersionMinor); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(body); + } + + function request_generator() { + return 'GET / HTTP/1.0\r\n\r\n'; + } + + function response_validator(server_response, client_got_eof, timed_out) { + var m = server_response.data.split('\r\n\r\n'); + assert.equal(m[1], body); + assert.equal(true, client_got_eof); + assert.equal(false, timed_out); + } + + test(handler, request_generator, response_validator); +})(); + +// +// Don't send HTTP/1.1 status lines to HTTP/1.0 clients. +// +// https://github.com/joyent/node/issues/1234 +// +(function() { + function handler(req, res) { + assert.equal('1.0', req.httpVersion); + assert.equal(1, req.httpVersionMajor); + assert.equal(0, req.httpVersionMinor); + res.sendDate = false; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Hello, '); res._send(''); + res.write('world!'); res._send(''); + res.end(); + } + + function request_generator() { + return ('GET / HTTP/1.0\r\n' + + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + + 'Host: 127.0.0.1:1337\r\n' + + 'Accept: */*\r\n' + + '\r\n'); + } + + function response_validator(server_response, client_got_eof, timed_out) { + var expected_response = ('HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + '\r\n' + + 'Hello, world!'); + + assert.equal(expected_response, server_response.data); + assert.equal(1, server_response.chunks.length); + assert.equal(true, client_got_eof); + assert.equal(false, timed_out); + } + + test(handler, request_generator, response_validator); +})(); + +(function() { + function handler(req, res) { + assert.equal('1.1', req.httpVersion); + assert.equal(1, req.httpVersionMajor); + assert.equal(1, req.httpVersionMinor); + res.sendDate = false; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Hello, '); res._send(''); + res.write('world!'); res._send(''); + res.end(); + } + + function request_generator() { + return ('GET / HTTP/1.1\r\n' + + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + + 'Connection: close\r\n' + + 'Host: 127.0.0.1:1337\r\n' + + 'Accept: */*\r\n' + + '\r\n'); + } + + function response_validator(server_response, client_got_eof, timed_out) { + var expected_response = ('HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + 'Transfer-Encoding: chunked\r\n' + + '\r\n' + + '7\r\n' + + 'Hello, \r\n' + + '6\r\n' + + 'world!\r\n' + + '0\r\n' + + '\r\n'); + + assert.equal(expected_response, server_response.data); + assert.equal(1, server_response.chunks.length); + assert.equal(true, client_got_eof); + assert.equal(false, timed_out); + } + + test(handler, request_generator, response_validator); +})(); diff --git a/test/parallel/test-http-304.js b/test/parallel/test-http-304.js new file mode 100644 index 000000000..fcef21aee --- /dev/null +++ b/test/parallel/test-http-304.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var childProcess = require('child_process'); + +var s = http.createServer(function(request, response) { + response.writeHead(304); + response.end(); +}); + +s.listen(common.PORT, function() { + childProcess.exec('curl -i http://127.0.0.1:' + common.PORT + '/', + function(err, stdout, stderr) { + if (err) throw err; + s.close(); + common.error('curled response correctly'); + common.error(common.inspect(stdout)); + }); +}); + +console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); diff --git a/test/parallel/test-http-abort-before-end.js b/test/parallel/test-http-abort-before-end.js new file mode 100644 index 000000000..11e424fbe --- /dev/null +++ b/test/parallel/test-http-abort-before-end.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +var server = http.createServer(function(req, res) { + assert(false); // should not be called +}); + +server.listen(common.PORT, function() { + var req = http.request({method: 'GET', host: '127.0.0.1', port: common.PORT}); + + req.on('error', function(ex) { + // https://github.com/joyent/node/issues/1399#issuecomment-2597359 + // abort() should emit an Error, not the net.Socket object + assert(ex instanceof Error); + }); + + req.abort(); + req.end(); + + server.close(); +}); diff --git a/test/parallel/test-http-abort-client.js b/test/parallel/test-http-abort-client.js new file mode 100644 index 000000000..f15238af1 --- /dev/null +++ b/test/parallel/test-http-abort-client.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +var server = http.Server(function(req, res) { + console.log('Server accepted request.'); + res.writeHead(200); + res.write('Part of my res.'); + + res.destroy(); +}); + +var responseClose = false; + +server.listen(common.PORT, function() { + var client = http.get({ + port: common.PORT, + headers: { connection: 'keep-alive' } + + }, function(res) { + server.close(); + + console.log('Got res: ' + res.statusCode); + console.dir(res.headers); + + res.on('data', function(chunk) { + console.log('Read ' + chunk.length + ' bytes'); + console.log(' chunk=%j', chunk.toString()); + }); + + res.on('end', function() { + console.log('Response ended.'); + }); + + res.on('aborted', function() { + console.log('Response aborted.'); + }); + + res.socket.on('close', function() { + console.log('socket closed, but not res'); + }) + + // it would be nice if this worked: + res.on('close', function() { + console.log('Response aborted'); + responseClose = true; + }); + }); +}); + + +process.on('exit', function() { + assert.ok(responseClose); +}); diff --git a/test/parallel/test-http-abort-queued.js b/test/parallel/test-http-abort-queued.js new file mode 100644 index 000000000..6d83cd41c --- /dev/null +++ b/test/parallel/test-http-abort-queued.js @@ -0,0 +1,104 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'), + common = require('../common'), + http = require('http'); + +var complete; + +var server = http.createServer(function (req, res) { + // We should not see the queued /thatotherone request within the server + // as it should be aborted before it is sent. + assert.equal(req.url, '/'); + + res.writeHead(200); + res.write('foo'); + + complete = complete || function () { + res.end(); + }; +}); + + +server.listen(common.PORT, function () { + console.log('listen', server.address().port); + + var agent = new http.Agent({maxSockets: 1}); + assert.equal(Object.keys(agent.sockets).length, 0); + + var options = { + hostname: 'localhost', + port: server.address().port, + method: 'GET', + path: '/', + agent: agent + }; + + var req1 = http.request(options); + req1.on('response', function(res1) { + assert.equal(Object.keys(agent.sockets).length, 1); + assert.equal(Object.keys(agent.requests).length, 0); + + var req2 = http.request({ + method: 'GET', + host: 'localhost', + port: server.address().port, + path: '/thatotherone', + agent: agent + }); + assert.equal(Object.keys(agent.sockets).length, 1); + assert.equal(Object.keys(agent.requests).length, 1); + + req2.on('error', function(err) { + // This is expected in response to our explicit abort call + assert.equal(err.code, 'ECONNRESET'); + }); + + req2.end(); + req2.abort(); + + assert.equal(Object.keys(agent.sockets).length, 1); + assert.equal(Object.keys(agent.requests).length, 1); + + console.log('Got res: ' + res1.statusCode); + console.dir(res1.headers); + + res1.on('data', function(chunk) { + console.log('Read ' + chunk.length + ' bytes'); + console.log(' chunk=%j', chunk.toString()); + complete(); + }); + + res1.on('end', function() { + console.log('Response ended.'); + + setTimeout(function() { + assert.equal(Object.keys(agent.sockets).length, 0); + assert.equal(Object.keys(agent.requests).length, 0); + + server.close(); + }, 100); + }); + }); + + req1.end(); +}); diff --git a/test/parallel/test-http-after-connect.js b/test/parallel/test-http-after-connect.js new file mode 100644 index 000000000..08b2c14a6 --- /dev/null +++ b/test/parallel/test-http-after-connect.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var serverConnected = false; +var serverRequests = 0; +var clientResponses = 0; + +var server = http.createServer(function(req, res) { + common.debug('Server got GET request'); + req.resume(); + ++serverRequests; + res.writeHead(200); + res.write(''); + setTimeout(function() { + res.end(req.url); + }, 50); +}); +server.on('connect', function(req, socket, firstBodyChunk) { + common.debug('Server got CONNECT request'); + serverConnected = true; + socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); + socket.resume(); + socket.on('end', function() { + socket.end(); + }); +}); +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + method: 'CONNECT', + path: 'google.com:80' + }); + req.on('connect', function(res, socket, firstBodyChunk) { + common.debug('Client got CONNECT response'); + socket.end(); + socket.on('end', function() { + doRequest(0); + doRequest(1); + }); + socket.resume(); + }); + req.end(); +}); + +function doRequest(i) { + var req = http.get({ + port: common.PORT, + path: '/request' + i + }, function(res) { + common.debug('Client got GET response'); + var data = ''; + res.setEncoding('utf8'); + res.on('data', function(chunk) { + data += chunk; + }); + res.on('end', function() { + assert.equal(data, '/request' + i); + ++clientResponses; + if (clientResponses === 2) { + server.close(); + } + }); + }); +} + +process.on('exit', function() { + assert(serverConnected); + assert.equal(serverRequests, 2); + assert.equal(clientResponses, 2); +}); diff --git a/test/parallel/test-http-agent-destroyed-socket.js b/test/parallel/test-http-agent-destroyed-socket.js new file mode 100644 index 000000000..be90bc677 --- /dev/null +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World\n'); +}).listen(common.PORT); + +var agent = new http.Agent({maxSockets: 1}); + +agent.on('free', function(socket, host, port) { + console.log('freeing socket. destroyed? ', socket.destroyed); +}); + +var requestOptions = { + agent: agent, + host: 'localhost', + port: common.PORT, + path: '/' +}; + +var request1 = http.get(requestOptions, function(response) { + // assert request2 is queued in the agent + var key = agent.getName(requestOptions); + assert(agent.requests[key].length === 1); + console.log('got response1'); + request1.socket.on('close', function() { + console.log('request1 socket closed'); + }); + response.pipe(process.stdout); + response.on('end', function() { + console.log('response1 done'); + ///////////////////////////////// + // + // THE IMPORTANT PART + // + // It is possible for the socket to get destroyed and other work + // to run before the 'close' event fires because it happens on + // nextTick. This example is contrived because it destroys the + // socket manually at just the right time, but at Voxer we have + // seen cases where the socket is destroyed by non-user code + // then handed out again by an agent *before* the 'close' event + // is triggered. + request1.socket.destroy(); + + response.once('close', function() { + // assert request2 was removed from the queue + assert(!agent.requests[key]); + console.log("waiting for request2.onSocket's nextTick"); + process.nextTick(function() { + // assert that the same socket was not assigned to request2, + // since it was destroyed. + assert(request1.socket !== request2.socket); + assert(!request2.socket.destroyed, 'the socket is destroyed'); + }); + }); + }); +}); + +var request2 = http.get(requestOptions, function(response) { + assert(!request2.socket.destroyed); + assert(request1.socket.destroyed); + // assert not reusing the same socket, since it was destroyed. + assert(request1.socket !== request2.socket); + console.log('got response2'); + var gotClose = false; + var gotResponseEnd = false; + request2.socket.on('close', function() { + console.log('request2 socket closed'); + gotClose = true; + done(); + }); + response.pipe(process.stdout); + response.on('end', function() { + console.log('response2 done'); + gotResponseEnd = true; + done(); + }); + + function done() { + if (gotResponseEnd && gotClose) + server.close(); + } +}); diff --git a/test/parallel/test-http-agent-false.js b/test/parallel/test-http-agent-false.js new file mode 100644 index 000000000..d897ab603 --- /dev/null +++ b/test/parallel/test-http-agent-false.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// sending `agent: false` when `port: null` is also passed in (i.e. the result of +// a `url.parse()` call with the default port used, 80 or 443), should not result +// in an assertion error... +var opts = { + host: '127.0.0.1', + port: null, + path: '/', + method: 'GET', + agent: false +}; + +var good = false; +process.on('exit', function() { + assert(good, 'expected either an "error" or "response" event'); +}); + +// we just want an "error" (no local HTTP server on port 80) or "response" +// to happen (user happens ot have HTTP server running on port 80). As long as the +// process doesn't crash from a C++ assertion then we're good. +var req = http.request(opts); +req.on('response', function(res) { + good = true; +}); +req.on('error', function(err) { + // an "error" event is ok, don't crash the process + good = true; +}); +req.end(); diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js new file mode 100644 index 000000000..f56027a72 --- /dev/null +++ b/test/parallel/test-http-agent-keepalive.js @@ -0,0 +1,145 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var Agent = require('_http_agent').Agent; +var EventEmitter = require('events').EventEmitter; + +var agent = new Agent({ + keepAlive: true, + keepAliveMsecs: 1000, + maxSockets: 5, + maxFreeSockets: 5 +}); + +var server = http.createServer(function (req, res) { + if (req.url === '/error') { + res.destroy(); + return; + } else if (req.url === '/remote_close') { + // cache the socket, close it after 100ms + var socket = res.connection; + setTimeout(function () { + socket.end(); + }, 100); + } + res.end('hello world'); +}); + +function get(path, callback) { + return http.get({ + host: 'localhost', + port: common.PORT, + agent: agent, + path: path + }, callback); +} + +var name = 'localhost:' + common.PORT + '::'; + +function checkDataAndSockets(body) { + assert.equal(body.toString(), 'hello world'); + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.freeSockets[name], undefined); +} + +function second() { + // request second, use the same socket + get('/second', function (res) { + assert.equal(res.statusCode, 200); + res.on('data', checkDataAndSockets); + res.on('end', function () { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.freeSockets[name], undefined); + process.nextTick(function () { + assert.equal(agent.sockets[name], undefined); + assert.equal(agent.freeSockets[name].length, 1); + remoteClose(); + }); + }); + }); +} + +function remoteClose() { + // mock remote server close the socket + get('/remote_close', function (res) { + assert.deepEqual(res.statusCode, 200); + res.on('data', checkDataAndSockets); + res.on('end', function () { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.freeSockets[name], undefined); + process.nextTick(function () { + assert.equal(agent.sockets[name], undefined); + assert.equal(agent.freeSockets[name].length, 1); + // waitting remote server close the socket + setTimeout(function () { + assert.equal(agent.sockets[name], undefined); + assert.equal(agent.freeSockets[name], undefined, + 'freeSockets is not empty'); + remoteError(); + }, 200); + }); + }); + }); +} + +function remoteError() { + // remove server will destroy ths socket + var req = get('/error', function (res) { + throw new Error('should not call this function'); + }); + req.on('error', function (err) { + assert.ok(err); + assert.equal(err.message, 'socket hang up'); + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.freeSockets[name], undefined); + // Wait socket 'close' event emit + setTimeout(function () { + assert.equal(agent.sockets[name], undefined); + assert.equal(agent.freeSockets[name], undefined); + done(); + }, 1); + }); +} + +function done() { + console.log('http keepalive agent test success.'); + process.exit(0); +} + +server.listen(common.PORT, function() { + // request first, and keep alive + get('/first', function (res) { + assert.equal(res.statusCode, 200); + res.on('data', checkDataAndSockets); + res.on('end', function () { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.freeSockets[name], undefined); + process.nextTick(function () { + assert.equal(agent.sockets[name], undefined); + assert.equal(agent.freeSockets[name].length, 1); + second(); + }); + }); + }); +}); diff --git a/test/parallel/test-http-agent-no-protocol.js b/test/parallel/test-http-agent-no-protocol.js new file mode 100644 index 000000000..fa224c5a7 --- /dev/null +++ b/test/parallel/test-http-agent-no-protocol.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var request = 0; +var response = 0; +process.on('exit', function() { + assert.equal(1, request, 'http server "request" callback was not called'); + assert.equal(1, response, 'http client "response" callback was not called'); +}); + +var server = http.createServer(function(req, res) { + res.end(); + request++; +}).listen(common.PORT, '127.0.0.1', function() { + var opts = url.parse('http://127.0.0.1:' + common.PORT + '/'); + + // remove the `protocol` field… the `http` module should fall back + // to "http:", as defined by the global, default `http.Agent` instance. + opts.agent = new http.Agent(); + opts.agent.protocol = null; + + http.get(opts, function (res) { + response++; + res.resume(); + server.close(); + }); +}); diff --git a/test/parallel/test-http-agent-null.js b/test/parallel/test-http-agent-null.js new file mode 100644 index 000000000..3f49cec0c --- /dev/null +++ b/test/parallel/test-http-agent-null.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var request = 0; +var response = 0; +process.on('exit', function() { + assert.equal(request, 1, 'http server "request" callback was not called'); + assert.equal(response, 1, 'http request "response" callback was not called'); +}); + +var server = http.createServer(function(req, res) { + request++; + res.end(); +}).listen(common.PORT, function() { + var options = { + agent: null, + port: this.address().port + }; + http.get(options, function(res) { + response++; + res.resume(); + server.close(); + }); +}); diff --git a/test/parallel/test-http-agent.js b/test/parallel/test-http-agent.js new file mode 100644 index 000000000..fc66dc49f --- /dev/null +++ b/test/parallel/test-http-agent.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.Server(function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + +var responses = 0; +var N = 10; +var M = 10; + +server.listen(common.PORT, function() { + for (var i = 0; i < N; i++) { + setTimeout(function() { + for (var j = 0; j < M; j++) { + http.get({ port: common.PORT, path: '/' }, function(res) { + console.log('%d %d', responses, res.statusCode); + if (++responses == N * M) { + console.error('Received all responses, closing server'); + server.close(); + } + res.resume(); + }).on('error', function(e) { + console.log('Error!', e); + process.exit(1); + }); + } + }, i); + } +}); + + +process.on('exit', function() { + assert.equal(N * M, responses); +}); diff --git a/test/parallel/test-http-allow-req-after-204-res.js b/test/parallel/test-http-allow-req-after-204-res.js new file mode 100644 index 000000000..225ff299e --- /dev/null +++ b/test/parallel/test-http-allow-req-after-204-res.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +// first 204 or 304 works, subsequent anything fails +var codes = [204, 200]; + +// Methods don't really matter, but we put in something realistic. +var methods = ['DELETE', 'DELETE']; + +var server = http.createServer(function(req, res) { + var code = codes.shift(); + assert.equal('number', typeof code); + assert.ok(code > 0); + console.error('writing %d response', code); + res.writeHead(code, {}); + res.end(); +}); + +function nextRequest() { + var method = methods.shift(); + console.error('writing request: %s', method); + + var request = http.request({ + port: common.PORT, + method: method, + path: '/' + }, function(response) { + response.on('end', function() { + if (methods.length == 0) { + console.error('close server'); + server.close(); + } else { + // throws error: + nextRequest(); + // works just fine: + //process.nextTick(nextRequest); + } + }); + response.resume(); + }); + request.end(); +} + +server.listen(common.PORT, nextRequest); diff --git a/test/parallel/test-http-bind-twice.js b/test/parallel/test-http-bind-twice.js new file mode 100644 index 000000000..59d69efaa --- /dev/null +++ b/test/parallel/test-http-bind-twice.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var gotError = false; + +process.on('exit', function() { + assert(gotError); +}); + +function dontCall() { + assert(false); +} + +var server1 = http.createServer(dontCall); +server1.listen(common.PORT, '127.0.0.1', function() {}); + +var server2 = http.createServer(dontCall); +server2.listen(common.PORT, '127.0.0.1', dontCall); + +server2.on('error', function(e) { + assert.equal(e.code, 'EADDRINUSE'); + server1.close(); + gotError = true; +}); + diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js new file mode 100644 index 000000000..bd9be8610 --- /dev/null +++ b/test/parallel/test-http-blank-header.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var gotReq = false; + +var server = http.createServer(function(req, res) { + common.error('got req'); + gotReq = true; + assert.equal('GET', req.method); + assert.equal('/blah', req.url); + assert.deepEqual({ + host: 'mapdevel.trolologames.ru:443', + origin: 'http://mapdevel.trolologames.ru', + cookie: '' + }, req.headers); +}); + + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('connect', function() { + common.error('client wrote message'); + c.write('GET /blah HTTP/1.1\r\n' + + 'Host: mapdevel.trolologames.ru:443\r\n' + + 'Cookie:\r\n' + + 'Origin: http://mapdevel.trolologames.ru\r\n' + + '\r\n\r\nhello world' + ); + }); + + c.on('end', function() { + c.end(); + }); + + c.on('close', function() { + common.error('client close'); + server.close(); + }); +}); + + +process.on('exit', function() { + assert.ok(gotReq); +}); diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js new file mode 100644 index 000000000..2e650d9b2 --- /dev/null +++ b/test/parallel/test-http-buffer-sanity.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +var bufferSize = 5 * 1024 * 1024; +var measuredSize = 0; + +var buffer = Buffer(bufferSize); +for (var i = 0; i < buffer.length; i++) { + buffer[i] = i % 256; +} + + +var web = http.Server(function(req, res) { + web.close(); + + console.log(req.headers); + + var i = 0; + + req.on('data', function(d) { + process.stdout.write(','); + measuredSize += d.length; + for (var j = 0; j < d.length; j++) { + assert.equal(buffer[i], d[j]); + i++; + } + }); + + + req.on('end', function() { + res.writeHead(200); + res.write('thanks'); + res.end(); + console.log('response with \'thanks\''); + }); + + req.connection.on('error', function(e) { + console.log('http server-side error: ' + e.message); + process.exit(1); + }); +}); + +var gotThanks = false; + +web.listen(common.PORT, function() { + console.log('Making request'); + + var req = http.request({ + port: common.PORT, + method: 'GET', + path: '/', + headers: { 'content-length': buffer.length } + }, function(res) { + console.log('Got response'); + res.setEncoding('utf8'); + res.on('data', function(string) { + assert.equal('thanks', string); + gotThanks = true; + }); + }); + req.end(buffer); +}); + + +process.on('exit', function() { + assert.equal(bufferSize, measuredSize); + assert.ok(gotThanks); +}); diff --git a/test/parallel/test-http-byteswritten.js b/test/parallel/test-http-byteswritten.js new file mode 100644 index 000000000..dedc2399c --- /dev/null +++ b/test/parallel/test-http-byteswritten.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var http = require('http'); + +var body = 'hello world\n'; + +var sawFinish = false; +process.on('exit', function() { + assert(sawFinish); + console.log('ok'); +}); + +var httpServer = http.createServer(function(req, res) { + httpServer.close(); + + res.on('finish', function() { + sawFinish = true; + assert(typeof(req.connection.bytesWritten) === 'number'); + assert(req.connection.bytesWritten > 0); + }); + res.writeHead(200, { 'Content-Type': 'text/plain' }); + + // Write 1.5mb to cause some requests to buffer + // Also, mix up the encodings a bit. + var chunk = new Array(1024 + 1).join('7'); + var bchunk = new Buffer(chunk); + for (var i = 0; i < 1024; i++) { + res.write(chunk); + res.write(bchunk); + res.write(chunk, 'hex'); + } + // Get .bytesWritten while buffer is not empty + assert(res.connection.bytesWritten > 0); + + res.end(body); +}); + +httpServer.listen(common.PORT, function() { + http.get({ port: common.PORT }); +}); + diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js new file mode 100644 index 000000000..24c5fa151 --- /dev/null +++ b/test/parallel/test-http-chunked-304.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +// RFC 2616, section 10.2.5: +// +// The 204 response MUST NOT contain a message-body, and thus is always +// terminated by the first empty line after the header fields. +// +// Likewise for 304 responses. Verify that no empty chunk is sent when +// the user explicitly sets a Transfer-Encoding header. + +test(204, function() { + test(304); +}); + +function test(statusCode, next) { + var server = http.createServer(function(req, res) { + res.writeHead(statusCode, { 'Transfer-Encoding': 'chunked' }); + res.end(); + server.close(); + }); + + server.listen(common.PORT, function() { + var conn = net.createConnection(common.PORT, function() { + conn.write('GET / HTTP/1.1\r\n\r\n'); + + var resp = ''; + conn.setEncoding('utf8'); + conn.on('data', function(data) { + resp += data; + }); + + conn.on('end', common.mustCall(function() { + assert.equal(/^Connection: close\r\n$/m.test(resp), true); + assert.equal(/^0\r\n$/m.test(resp), false); + if (next) process.nextTick(next); + })); + }); + }); +} diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js new file mode 100644 index 000000000..c5def3de7 --- /dev/null +++ b/test/parallel/test-http-chunked.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + + '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + + '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + + '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + + '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + + '有效的改善了岭南地区落后的政治、经济现状。'; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); + res.end(UTF8_STRING, 'utf8'); +}); +server.listen(common.PORT, function() { + var data = ''; + var get = http.get({ + path: '/', + host: 'localhost', + port: common.PORT + }, function(x) { + x.setEncoding('utf8'); + x.on('data', function(c) {data += c}); + x.on('error', function(e) { + throw e; + }); + x.on('end', function() { + assert.equal('string', typeof data); + console.log('here is the response:'); + assert.equal(UTF8_STRING, data); + console.log(data); + server.close(); + }); + }); + get.on('error', function(e) {throw e}); + get.end(); + +}); diff --git a/test/parallel/test-http-client-abort.js b/test/parallel/test-http-client-abort.js new file mode 100644 index 000000000..ae0ee2769 --- /dev/null +++ b/test/parallel/test-http-client-abort.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var clientAborts = 0; + +var server = http.Server(function(req, res) { + console.log('Got connection'); + res.writeHead(200); + res.write('Working on it...'); + + // I would expect an error event from req or res that the client aborted + // before completing the HTTP request / response cycle, or maybe a new + // event like "aborted" or something. + req.on('aborted', function() { + clientAborts++; + console.log('Got abort ' + clientAborts); + if (clientAborts === N) { + console.log('All aborts detected, you win.'); + server.close(); + } + }); + + // since there is already clientError, maybe that would be appropriate, + // since "error" is magical + req.on('clientError', function() { + console.log('Got clientError'); + }); +}); + +var responses = 0; +var N = 16; +var requests = []; + +server.listen(common.PORT, function() { + console.log('Server listening.'); + + for (var i = 0; i < N; i++) { + console.log('Making client ' + i); + var options = { port: common.PORT, path: '/?id=' + i }; + var req = http.get(options, function(res) { + console.log('Client response code ' + res.statusCode); + + res.resume(); + if (++responses == N) { + console.log('All clients connected, destroying.'); + requests.forEach(function(outReq) { + console.log('abort'); + outReq.abort(); + }); + } + }); + + requests.push(req); + } +}); + +process.on('exit', function() { + assert.equal(N, clientAborts); +}); diff --git a/test/parallel/test-http-client-abort2.js b/test/parallel/test-http-client-abort2.js new file mode 100644 index 000000000..17efb7e08 --- /dev/null +++ b/test/parallel/test-http-client-abort2.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + res.end('Hello'); +}); + +server.listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + res.on('data', function(data) { + req.abort(); + server.close(); + }); + }); +}); + diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js new file mode 100644 index 000000000..49ff77fc9 --- /dev/null +++ b/test/parallel/test-http-client-agent.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var name = http.globalAgent.getName({ port: common.PORT }); +var max = 3; +var count = 0; + +var server = http.Server(function(req, res) { + if (req.url === '/0') { + setTimeout(function() { + res.writeHead(200); + res.end('Hello, World!'); + }, 100); + } else { + res.writeHead(200); + res.end('Hello, World!'); + } +}); +server.listen(common.PORT, function() { + for (var i = 0; i < max; ++i) { + request(i); + } +}); + +function request(i) { + var req = http.get({ + port: common.PORT, + path: '/' + i + }, function(res) { + var socket = req.socket; + socket.on('close', function() { + ++count; + if (count < max) { + assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); + } else { + assert(!http.globalAgent.sockets.hasOwnProperty(name)); + assert(!http.globalAgent.requests.hasOwnProperty(name)); + server.close(); + } + }); + res.resume(); + }); +} + +process.on('exit', function() { + assert.equal(count, max); +}); diff --git a/test/parallel/test-http-client-default-headers-exist.js b/test/parallel/test-http-client-default-headers-exist.js new file mode 100644 index 000000000..24470b95d --- /dev/null +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expectedHeaders = { + 'DELETE': ['host', 'connection'], + 'GET': ['host', 'connection'], + 'HEAD': ['host', 'connection'], + 'OPTIONS': ['host', 'connection'], + 'POST': ['host', 'connection', 'transfer-encoding'], + 'PUT': ['host', 'connection', 'transfer-encoding'] +}; + +var expectedMethods = Object.keys(expectedHeaders); + +var requestCount = 0; + +var server = http.createServer(function(req, res) { + requestCount++; + res.end(); + + assert(expectedHeaders.hasOwnProperty(req.method), + req.method + ' was an unexpected method'); + + var requestHeaders = Object.keys(req.headers); + requestHeaders.forEach(function(header) { + assert(expectedHeaders[req.method].indexOf(header.toLowerCase()) !== -1, + header + ' shoud not exist for method ' + req.method); + }); + + assert(requestHeaders.length === expectedHeaders[req.method].length, + 'some headers were missing for method: ' + req.method); + + if (expectedMethods.length === requestCount) + server.close(); +}); + +server.listen(common.PORT, function() { + expectedMethods.forEach(function(method) { + http.request({ + method: method, + port: common.PORT + }).end(); + }); +}); diff --git a/test/parallel/test-http-client-encoding.js b/test/parallel/test-http-client-encoding.js new file mode 100644 index 000000000..104bf28e2 --- /dev/null +++ b/test/parallel/test-http-client-encoding.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +http.createServer(function(req, res) { + res.end('ok\n'); + this.close(); +}).listen(common.PORT, test); + +function test() { + http.request({ + port: common.PORT, + encoding: 'utf8' + }, function(res) { + res.pipe(process.stdout); + }).end(); +} diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js new file mode 100644 index 000000000..451f5eeaa --- /dev/null +++ b/test/parallel/test-http-client-get-url.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var seen_req = false; + +var server = http.createServer(function(req, res) { + assert.equal('GET', req.method); + assert.equal('/foo?bar', req.url); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + server.close(); + seen_req = true; +}); + +server.listen(common.PORT, function() { + http.get('http://127.0.0.1:' + common.PORT + '/foo?bar'); +}); + +process.on('exit', function() { + assert(seen_req); +}); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js new file mode 100644 index 000000000..9896ca225 --- /dev/null +++ b/test/parallel/test-http-client-parse-error.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +var connects = 0; +var parseErrors = 0; + +// Create a TCP server +net.createServer(function(c) { + console.log('connection'); + if (++connects === 1) { + c.end('HTTP/1.1 302 Object Moved\r\nContent-Length: 0\r\n\r\nhi world'); + } else { + c.end('bad http - should trigger parse error\r\n'); + this.close(); + } +}).listen(common.PORT, '127.0.0.1', function() { + for (var i = 0; i < 2; i++) { + http.request({ + host: '127.0.0.1', + port: common.PORT, + method: 'GET', + path: '/' + }).on('error', function(e) { + console.log('got error from client'); + assert.ok(e.message.indexOf('Parse Error') >= 0); + assert.equal(e.code, 'HPE_INVALID_CONSTANT'); + parseErrors++; + }).end(); + } +}); + +process.on('exit', function() { + assert.equal(connects, 2); + assert.equal(parseErrors, 2); +}); diff --git a/test/parallel/test-http-client-pipe-end.js b/test/parallel/test-http-client-pipe-end.js new file mode 100644 index 000000000..51edebbe1 --- /dev/null +++ b/test/parallel/test-http-client-pipe-end.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// see https://github.com/joyent/node/issues/3257 + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + req.resume(); + req.once('end', function() { + res.writeHead(200); + res.end(); + server.close(); + }); +}); + +server.listen(common.PIPE, function() { + var req = http.request({ + socketPath: common.PIPE, + headers: {'Content-Length':'1'}, + method: 'POST', + path: '/' + }); + + req.write('.'); + + sched(function() { req.end() }, 5); +}); + +// schedule a callback after `ticks` event loop ticks +function sched(cb, ticks) { + function fn() { + if (--ticks) + setImmediate(fn); + else + cb(); + } + setImmediate(fn); +} diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js new file mode 100644 index 000000000..6b7c508c3 --- /dev/null +++ b/test/parallel/test-http-client-race-2.js @@ -0,0 +1,118 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +// +// Slight variation on test-http-client-race to test for another race +// condition involving the parsers FreeList used internally by http.Client. +// + +var body1_s = '1111111111111111'; +var body2_s = '22222'; +var body3_s = '3333333333333333333'; + +var server = http.createServer(function(req, res) { + var pathname = url.parse(req.url).pathname; + + var body; + switch (pathname) { + case '/1': body = body1_s; break; + case '/2': body = body2_s; break; + default: body = body3_s; + } + + res.writeHead(200, + {'Content-Type': 'text/plain', 'Content-Length': body.length}); + res.end(body); +}); +server.listen(common.PORT); + +var body1 = ''; +var body2 = ''; +var body3 = ''; + +server.on('listening', function() { + var client = http.createClient(common.PORT); + + // + // Client #1 is assigned Parser #1 + // + var req1 = client.request('/1'); + req1.end(); + req1.on('response', function(res1) { + res1.setEncoding('utf8'); + + res1.on('data', function(chunk) { + body1 += chunk; + }); + + res1.on('end', function() { + // + // Delay execution a little to allow the 'close' event to be processed + // (required to trigger this bug!) + // + setTimeout(function() { + // + // The bug would introduce itself here: Client #2 would be allocated the + // parser that previously belonged to Client #1. But we're not finished + // with Client #1 yet! + // + var client2 = http.createClient(common.PORT); + + // + // At this point, the bug would manifest itself and crash because the + // internal state of the parser was no longer valid for use by Client #1 + // + var req2 = client.request('/2'); + req2.end(); + req2.on('response', function(res2) { + res2.setEncoding('utf8'); + res2.on('data', function(chunk) { body2 += chunk; }); + res2.on('end', function() { + + // + // Just to be really sure we've covered all our bases, execute a + // request using client2. + // + var req3 = client2.request('/3'); + req3.end(); + req3.on('response', function(res3) { + res3.setEncoding('utf8'); + res3.on('data', function(chunk) { body3 += chunk }); + res3.on('end', function() { server.close(); }); + }); + }); + }); + }, 500); + }); + }); +}); + +process.on('exit', function() { + assert.equal(body1_s, body1); + assert.equal(body2_s, body2); + assert.equal(body3_s, body3); +}); + diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js new file mode 100644 index 000000000..0f50c8e84 --- /dev/null +++ b/test/parallel/test-http-client-race.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var body1_s = '1111111111111111'; +var body2_s = '22222'; + +var server = http.createServer(function(req, res) { + var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; + res.writeHead(200, + {'Content-Type': 'text/plain', 'Content-Length': body.length}); + res.end(body); +}); +server.listen(common.PORT); + +var body1 = ''; +var body2 = ''; + +server.on('listening', function() { + var req1 = http.request({ port: common.PORT, path: '/1' }); + req1.end(); + req1.on('response', function(res1) { + res1.setEncoding('utf8'); + + res1.on('data', function(chunk) { + body1 += chunk; + }); + + res1.on('end', function() { + var req2 = http.request({ port: common.PORT, path: '/2' }); + req2.end(); + req2.on('response', function(res2) { + res2.setEncoding('utf8'); + res2.on('data', function(chunk) { body2 += chunk; }); + res2.on('end', function() { server.close(); }); + }); + }); + }); +}); + +process.on('exit', function() { + assert.equal(body1_s, body1); + assert.equal(body2_s, body2); +}); diff --git a/test/parallel/test-http-client-readable.js b/test/parallel/test-http-client-readable.js new file mode 100644 index 000000000..2b5f67562 --- /dev/null +++ b/test/parallel/test-http-client-readable.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +var Duplex = require('stream').Duplex; + +function FakeAgent() { + http.Agent.call(this); +} +util.inherits(FakeAgent, http.Agent); + +FakeAgent.prototype.createConnection = function createConnection() { + var s = new Duplex(); + var once = false; + + s._read = function read() { + if (once) + return this.push(null); + once = true; + + this.push('HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\n\r\n'); + this.push('b\r\nhello world\r\n'); + this.readable = false; + this.push('0\r\n\r\n'); + }; + + // Blackhole + s._write = function write(data, enc, cb) { + cb(); + }; + + s.destroy = s.destroySoon = function destroy() { + this.writable = false; + }; + + return s; +}; + +var received = ''; +var ended = 0; + +var req = http.request({ + agent: new FakeAgent() +}, function(res) { + res.on('data', function(chunk) { + received += chunk; + }); + + res.on('end', function() { + ended++; + }); +}); +req.end(); + +process.on('exit', function() { + assert.equal(received, 'hello world'); + assert.equal(ended, 1); +}); diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js new file mode 100644 index 000000000..e5a39913f --- /dev/null +++ b/test/parallel/test-http-client-response-domain.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + http = require('http'), + domain = require('domain'); + +var gotDomainError = false; +var d; + +process.on('exit', function() { + assert(gotDomainError); +}); + +// first fire up a simple HTTP server +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.end(); + server.close(); +}); +server.listen(common.PIPE, function() { + // create a domain + d = domain.create(); + d.run(test); +}); + +function test() { + + d.on('error', function(err) { + gotDomainError = true; + assert.equal('should be caught by domain', err.message); + }); + + var req = http.get({ + socketPath: common.PIPE, + headers: {'Content-Length':'1'}, + method: 'POST', + path: '/' + }); + req.on('response', function(res) { + res.on('end', function() { + res.emit('error', new Error('should be caught by domain')); + }); + res.resume(); + }); + req.end(); +} diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js new file mode 100644 index 000000000..79d0a2424 --- /dev/null +++ b/test/parallel/test-http-client-timeout-agent.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var request_number = 0; +var requests_sent = 0; +var requests_done = 0; +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', +}; + +//http.globalAgent.maxSockets = 15; + +var server = http.createServer(function(req, res) { + var m = /\/(.*)/.exec(req.url), + reqid = parseInt(m[1], 10); + if ( reqid % 2 ) { + // do not reply the request + } else { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(reqid.toString()); + res.end(); + } + request_number+=1; +}); + +server.listen(options.port, options.host, function() { + var req; + + for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { + options.path = '/' + requests_sent; + req = http.request(options); + req.id = requests_sent; + req.on('response', function(res) { + res.on('data', function(data) { + console.log('res#'+this.req.id+' data:'+data); + }); + res.on('end', function(data) { + console.log('res#'+this.req.id+' end'); + requests_done += 1; + }); + }); + req.on('close', function() { + console.log('req#'+this.id+' close'); + }); + req.on('error', function() { + console.log('req#'+this.id+' error'); + this.destroy(); + }); + req.setTimeout(50, function () { + var req = this; + console.log('req#'+this.id + ' timeout'); + req.abort(); + requests_done += 1; + }); + req.end(); + } + + setTimeout(function maybeDone() { + if (requests_done >= requests_sent) { + setTimeout(function() { + server.close(); + }, 100); + } else { + setTimeout(maybeDone, 100); + } + }, 100); +}); + +process.on('exit', function() { + console.error('done=%j sent=%j', requests_done, requests_sent); + assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); +}); diff --git a/test/parallel/test-http-client-timeout-event.js b/test/parallel/test-http-client-timeout-event.js new file mode 100644 index 000000000..e3e37f699 --- /dev/null +++ b/test/parallel/test-http-client-timeout-event.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', + path: '/' +}; + +var server = http.createServer(function(req, res) { + // this space intentionally left blank +}); + +server.listen(options.port, options.host, function() { + var req = http.request(options, function(res) { + // this space intentionally left blank + }); + req.on('error', function() { + // this space is intentionally left blank + }); + req.on('close', function() { + server.close(); + }); + + var timeout_events = 0; + req.setTimeout(1); + req.on('timeout', function () { + timeout_events += 1; + }); + setTimeout(function () { + req.destroy(); + assert.equal(timeout_events, 1); + }, 100); + setTimeout(function () { + req.end(); + }, 50); +}); diff --git a/test/parallel/test-http-client-timeout-with-data.js b/test/parallel/test-http-client-timeout-with-data.js new file mode 100644 index 000000000..4e1aae6ff --- /dev/null +++ b/test/parallel/test-http-client-timeout-with-data.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var ntimeouts = 0; +var nchunks = 0; + +process.on('exit', function() { + assert.equal(ntimeouts, 1); + assert.equal(nchunks, 2); +}); + +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', + path: '/' +}; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length':'2'}); + res.write('*'); + setTimeout(function() { res.end('*') }, 100); +}); + +server.listen(options.port, options.host, function() { + var req = http.request(options, onresponse); + req.end(); + + function onresponse(res) { + req.setTimeout(50, function() { + assert.equal(nchunks, 1); // should have received the first chunk by now + ntimeouts++; + }); + + res.on('data', function(data) { + assert.equal('' + data, '*'); + nchunks++; + }); + + res.on('end', function() { + assert.equal(nchunks, 2); + server.close(); + }); + } +}); diff --git a/test/parallel/test-http-client-timeout.js b/test/parallel/test-http-client-timeout.js new file mode 100644 index 000000000..98eb5539e --- /dev/null +++ b/test/parallel/test-http-client-timeout.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var options = { + method: 'GET', + port: common.PORT, + host: '127.0.0.1', + path: '/' +}; + +var server = http.createServer(function(req, res) { + // this space intentionally left blank +}); + +server.listen(options.port, options.host, function() { + var req = http.request(options, function(res) { + // this space intentionally left blank + }); + req.on('close', function() { + server.close(); + }); + function destroy() { + req.destroy(); + } + req.setTimeout(1, destroy); + req.on('error', destroy); + req.end(); +}); diff --git a/test/parallel/test-http-client-unescaped-path.js b/test/parallel/test-http-client-unescaped-path.js new file mode 100644 index 000000000..376bca19c --- /dev/null +++ b/test/parallel/test-http-client-unescaped-path.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +assert.throws(function() { + // Path with spaces in it should throw. + http.get({ path: 'bad path' }, assert.fail); +}, /contains unescaped characters/); diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js new file mode 100644 index 000000000..d607ea88b --- /dev/null +++ b/test/parallel/test-http-client-upload-buf.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var N = 1024; +var bytesReceived = 0; +var server_req_complete = false; +var client_res_complete = false; + +var server = http.createServer(function(req, res) { + assert.equal('POST', req.method); + + req.on('data', function(chunk) { + bytesReceived += chunk.length; + }); + + req.on('end', function() { + server_req_complete = true; + console.log('request complete from server'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/' + }, function(res) { + res.setEncoding('utf8'); + res.on('data', function(chunk) { + console.log(chunk); + }); + res.on('end', function() { + client_res_complete = true; + server.close(); + }); + }); + + req.write(new Buffer(N)); + req.end(); + + common.error('client finished sending request'); +}); + +process.on('exit', function() { + assert.equal(N, bytesReceived); + assert.equal(true, server_req_complete); + assert.equal(true, client_res_complete); +}); diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js new file mode 100644 index 000000000..912ca9608 --- /dev/null +++ b/test/parallel/test-http-client-upload.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var sent_body = ''; +var server_req_complete = false; +var client_res_complete = false; + +var server = http.createServer(function(req, res) { + assert.equal('POST', req.method); + req.setEncoding('utf8'); + + req.on('data', function(chunk) { + console.log('server got: ' + JSON.stringify(chunk)); + sent_body += chunk; + }); + + req.on('end', function() { + server_req_complete = true; + console.log('request complete from server'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/' + }, function(res) { + res.setEncoding('utf8'); + res.on('data', function(chunk) { + console.log(chunk); + }); + res.on('end', function() { + client_res_complete = true; + server.close(); + }); + }); + + req.write('1\n'); + req.write('2\n'); + req.write('3\n'); + req.end(); + + common.error('client finished sending request'); +}); + +process.on('exit', function() { + assert.equal('1\n2\n3\n', sent_body); + assert.equal(true, server_req_complete); + assert.equal(true, client_res_complete); +}); diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js new file mode 100644 index 000000000..9c293721c --- /dev/null +++ b/test/parallel/test-http-conn-reset.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var caughtError = false; + +var options = { + host: '127.0.0.1', + port: common.PORT +}; + +// start a tcp server that closes incoming connections immediately +var server = net.createServer(function(client) { + client.destroy(); + server.close(); +}); +server.listen(options.port, options.host, onListen); + +// do a GET request, expect it to fail +function onListen() { + var req = http.request(options, function(res) { + assert.ok(false, 'this should never run'); + }); + req.on('error', function(err) { + assert.equal(err.code, 'ECONNRESET'); + caughtError = true; + }); + req.end(); +} + +process.on('exit', function() { + assert.equal(caughtError, true); +}); + diff --git a/test/parallel/test-http-connect.js b/test/parallel/test-http-connect.js new file mode 100644 index 000000000..3643cec18 --- /dev/null +++ b/test/parallel/test-http-connect.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var serverGotConnect = false; +var clientGotConnect = false; + +var server = http.createServer(function(req, res) { + assert(false); +}); +server.on('connect', function(req, socket, firstBodyChunk) { + assert.equal(req.method, 'CONNECT'); + assert.equal(req.url, 'google.com:443'); + common.debug('Server got CONNECT request'); + serverGotConnect = true; + + socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); + + var data = firstBodyChunk.toString(); + socket.on('data', function(buf) { + data += buf.toString(); + }); + socket.on('end', function() { + socket.end(data); + }); +}); +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + method: 'CONNECT', + path: 'google.com:443' + }, function(res) { + assert(false); + }); + + var clientRequestClosed = false; + req.on('close', function() { + clientRequestClosed = true; + }); + + req.on('connect', function(res, socket, firstBodyChunk) { + common.debug('Client got CONNECT request'); + clientGotConnect = true; + + // Make sure this request got removed from the pool. + var name = 'localhost:' + common.PORT; + assert(!http.globalAgent.sockets.hasOwnProperty(name)); + assert(!http.globalAgent.requests.hasOwnProperty(name)); + + // Make sure this socket has detached. + assert(!socket.ondata); + assert(!socket.onend); + assert.equal(socket.listeners('connect').length, 0); + assert.equal(socket.listeners('data').length, 0); + + // the stream.Duplex onend listener + // allow 0 here, so that i can run the same test on streams1 impl + assert(socket.listeners('end').length <= 1); + + assert.equal(socket.listeners('free').length, 0); + assert.equal(socket.listeners('close').length, 0); + assert.equal(socket.listeners('error').length, 0); + assert.equal(socket.listeners('agentRemove').length, 0); + + var data = firstBodyChunk.toString(); + socket.on('data', function(buf) { + data += buf.toString(); + }); + socket.on('end', function() { + assert.equal(data, 'HeadBody'); + assert(clientRequestClosed); + server.close(); + }); + socket.write('Body'); + socket.end(); + }); + + // It is legal for the client to send some data intended for the server + // before the "200 Connection established" (or any other success or + // error code) is received. + req.write('Head'); + req.end(); +}); + +process.on('exit', function() { + assert.ok(serverGotConnect); + assert.ok(clientGotConnect); +}); diff --git a/test/parallel/test-http-contentLength0.js b/test/parallel/test-http-contentLength0.js new file mode 100644 index 000000000..c7f7b6b66 --- /dev/null +++ b/test/parallel/test-http-contentLength0.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); + +// Simple test of Node's HTTP Client choking on a response +// with a 'Content-Length: 0 ' response header. +// I.E. a space character after the 'Content-Length' throws an `error` event. + + +var s = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': '0 '}); + res.end(); +}); +s.listen(common.PORT, function() { + + var request = http.request({ port: common.PORT }, function(response) { + console.log('STATUS: ' + response.statusCode); + s.close(); + response.resume(); + }); + + request.end(); +}); diff --git a/test/parallel/test-http-createConnection.js b/test/parallel/test-http-createConnection.js new file mode 100644 index 000000000..bc29d9aee --- /dev/null +++ b/test/parallel/test-http-createConnection.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var create = 0; +var response = 0; +process.on('exit', function() { + assert.equal(1, create, 'createConnection() http option was not called'); + assert.equal(1, response, 'http server "request" callback was not called'); +}); + +var server = http.createServer(function(req, res) { + res.end(); + response++; +}).listen(common.PORT, '127.0.0.1', function() { + http.get({ createConnection: createConnection }, function (res) { + res.resume(); + server.close(); + }); +}); + +function createConnection() { + create++; + return net.createConnection(common.PORT, '127.0.0.1'); +} diff --git a/test/parallel/test-http-curl-chunk-problem.js b/test/parallel/test-http-curl-chunk-problem.js new file mode 100644 index 000000000..701624633 --- /dev/null +++ b/test/parallel/test-http-curl-chunk-problem.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +// http://groups.google.com/group/nodejs/browse_thread/thread/f66cd3c960406919 +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var cp = require('child_process'); +var fs = require('fs'); + +var filename = require('path').join(common.tmpDir, 'big'); + +var count = 0; +function maybeMakeRequest() { + if (++count < 2) return; + console.log('making curl request'); + var cmd = 'curl http://127.0.0.1:' + common.PORT + '/ | openssl sha1'; + cp.exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + var hex = stdout.match(/([A-Fa-f0-9]{40})/)[0]; + assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', hex); + console.log('got the correct response'); + fs.unlink(filename); + server.close(); + }); +} + + +var ddcmd = common.ddCommand(filename, 10240); +console.log('dd command: ', ddcmd); + +cp.exec(ddcmd, function(err, stdout, stderr) { + if (err) throw err; + maybeMakeRequest(); +}); + + +var server = http.createServer(function(req, res) { + res.writeHead(200); + + // Create the subprocess + var cat = cp.spawn('cat', [filename]); + + // Stream the data through to the response as binary chunks + cat.stdout.on('data', function(data) { + res.write(data); + }); + + // End the response on exit (and log errors) + cat.on('exit', function(code) { + if (code !== 0) { + console.error('subprocess exited with code ' + code); + process.exit(1); + } + res.end(); + }); + +}); + +server.listen(common.PORT, maybeMakeRequest); + +console.log('Server running at http://localhost:8080'); diff --git a/test/parallel/test-http-date-header.js b/test/parallel/test-http-date-header.js new file mode 100644 index 000000000..b11507c01 --- /dev/null +++ b/test/parallel/test-http-date-header.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var testResBody = 'other stuff!\n'; + +var server = http.createServer(function(req, res) { + assert.ok(! ('date' in req.headers), + 'Request headers contained a Date.'); + res.writeHead(200, { + 'Content-Type': 'text/plain' + }); + res.end(testResBody); +}); +server.listen(common.PORT); + + +server.addListener('listening', function() { + var options = { + port: common.PORT, + path: '/', + method: 'GET' + }; + var req = http.request(options, function(res) { + assert.ok('date' in res.headers, + 'Response headers didn\'t contain a Date.'); + res.addListener('end', function() { + server.close(); + process.exit(); + }); + res.resume(); + }); + req.end(); +}); diff --git a/test/parallel/test-http-default-encoding.js b/test/parallel/test-http-default-encoding.js new file mode 100644 index 000000000..b06f7c83a --- /dev/null +++ b/test/parallel/test-http-default-encoding.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expected = 'This is a unicode text: سلام'; +var result = ''; + +var server = http.Server(function(req, res) { + req.setEncoding('utf8'); + req.on('data', function(chunk) { + result += chunk; + }).on('end', function() { + clearTimeout(timeout); + server.close(); + }); + + var timeout = setTimeout(function() { + process.exit(1); + }, 100); + + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(common.PORT, function() { + http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }, function(res) { + console.log(res.statusCode); + res.resume(); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }).end(expected); +}); + +process.on('exit', function() { + assert.equal(expected, result); +}); diff --git a/test/parallel/test-http-default-port.js b/test/parallel/test-http-default-port.js new file mode 100644 index 000000000..ec79de2ae --- /dev/null +++ b/test/parallel/test-http-default-port.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var common = require('../common'); +var http = require('http'), + https = require('https'), + PORT = common.PORT, + SSLPORT = common.PORT + 1, + assert = require('assert'), + hostExpect = 'localhost', + fs = require('fs'), + path = require('path'), + fixtures = path.resolve(__dirname, '../fixtures/keys'), + options = { + key: fs.readFileSync(fixtures + '/agent1-key.pem'), + cert: fs.readFileSync(fixtures + '/agent1-cert.pem') + }, + gotHttpsResp = false, + gotHttpResp = false; + +process.on('exit', function() { + assert(gotHttpsResp); + assert(gotHttpResp); + console.log('ok'); +}); + +http.globalAgent.defaultPort = PORT; +https.globalAgent.defaultPort = SSLPORT; + +http.createServer(function(req, res) { + assert.equal(req.headers.host, hostExpect); + assert.equal(req.headers['x-port'], PORT); + res.writeHead(200); + res.end('ok'); + this.close(); +}).listen(PORT, function() { + http.get({ + host: 'localhost', + headers: { + 'x-port': PORT + } + }, function(res) { + gotHttpResp = true; + res.resume(); + }); +}); + +https.createServer(options, function(req, res) { + assert.equal(req.headers.host, hostExpect); + assert.equal(req.headers['x-port'], SSLPORT); + res.writeHead(200); + res.end('ok'); + this.close(); +}).listen(SSLPORT, function() { + var req = https.get({ + host: 'localhost', + rejectUnauthorized: false, + headers: { + 'x-port': SSLPORT + } + }, function(res) { + gotHttpsResp = true; + res.resume(); + }); +}); diff --git a/test/parallel/test-http-destroyed-socket-write2.js b/test/parallel/test-http-destroyed-socket-write2.js new file mode 100644 index 000000000..3347f3ccc --- /dev/null +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// Verify that ECONNRESET is raised when writing to a http request +// where the server has ended the socket. + +var http = require('http'); +var net = require('net'); +var server = http.createServer(function(req, res) { + setImmediate(function() { + res.destroy(); + }); +}); + +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }); + + var timer = setImmediate(write); + var writes = 0; + + function write() { + if (++writes === 128) { + clearTimeout(timer); + req.end(); + test(); + } else { + timer = setImmediate(write); + req.write('hello'); + } + } + + var gotError = false; + var sawData = false; + var sawEnd = false; + + req.on('error', function(er) { + assert(!gotError); + gotError = true; + switch (er.code) { + // This is the expected case + case 'ECONNRESET': + // On windows this sometimes manifests as ECONNABORTED + case 'ECONNABORTED': + break; + default: + assert.strictEqual(er.code, + 'ECONNRESET', + 'Writing to a torn down client should RESET or ABORT'); + break; + } + clearTimeout(timer); + console.log('ECONNRESET was raised after %d writes', writes); + test(); + }); + + req.on('response', function(res) { + res.on('data', function(chunk) { + console.error('saw data: ' + chunk); + sawData = true; + }); + res.on('end', function() { + console.error('saw end'); + sawEnd = true; + }); + }); + + var closed = false; + + function test() { + if (closed) + return; + + server.close(); + closed = true; + + if (req.output.length || req.outputEncodings.length) + console.error('bad happened', req.output, req.outputEncodings); + + assert.equal(req.output.length, 0); + assert.equal(req.outputEncodings, 0); + assert(gotError); + assert(!sawData); + assert(!sawEnd); + console.log('ok'); + } +}); diff --git a/test/parallel/test-http-dns-error.js b/test/parallel/test-http-dns-error.js new file mode 100644 index 000000000..fc6d6b89e --- /dev/null +++ b/test/parallel/test-http-dns-error.js @@ -0,0 +1,68 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var https = require('https'); + +var expected_bad_requests = 0; +var actual_bad_requests = 0; + +var host = '********'; +host += host; +host += host; +host += host; +host += host; +host += host; + +function do_not_call() { + throw new Error('This function should not have been called.'); +} + +function test(mod) { + expected_bad_requests += 2; + + // Bad host name should not throw an uncatchable exception. + // Ensure that there is time to attach an error listener. + var req = mod.get({host: host, port: 42}, do_not_call); + req.on('error', function(err) { + assert.equal(err.code, 'ENOTFOUND'); + actual_bad_requests++; + }); + // http.get() called req.end() for us + + var req = mod.request({method: 'GET', host: host, port: 42}, do_not_call); + req.on('error', function(err) { + assert.equal(err.code, 'ENOTFOUND'); + actual_bad_requests++; + }); + req.end(); +} + +test(https); +test(http); + +process.on('exit', function() { + assert.equal(actual_bad_requests, expected_bad_requests); +}); + diff --git a/test/parallel/test-http-end-throw-socket-handling.js b/test/parallel/test-http-end-throw-socket-handling.js new file mode 100644 index 000000000..50aa97ff1 --- /dev/null +++ b/test/parallel/test-http-end-throw-socket-handling.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// Make sure that throwing in 'end' handler doesn't lock +// up the socket forever. +// +// This is NOT a good way to handle errors in general, but all +// the same, we should not be so brittle and easily broken. + +var http = require('http'); + +var n = 0; +var server = http.createServer(function(req, res) { + if (++n === 10) server.close(); + res.end('ok'); +}); + +server.listen(common.PORT, function() { + for (var i = 0; i < 10; i++) { + var options = { port: common.PORT }; + + var req = http.request(options, function (res) { + res.resume() + res.on('end', function() { + throw new Error('gleep glorp'); + }); + }); + req.end(); + } +}); + +setTimeout(function() { + process.removeListener('uncaughtException', catcher); + throw new Error('Taking too long!'); +}, 1000).unref(); + +process.on('uncaughtException', catcher); +var errors = 0; +function catcher() { + errors++; +} + +process.on('exit', function() { + assert.equal(errors, 10); + console.log('ok'); +}); diff --git a/test/parallel/test-http-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js new file mode 100644 index 000000000..95d6fdc95 --- /dev/null +++ b/test/parallel/test-http-eof-on-connect.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +// This is a regression test for https://github.com/joyent/node/issues/44 +// It is separate from test-http-malformed-request.js because it is only +// reproduceable on the first packet on the first connection to a server. + +var server = http.createServer(function(req, res) {}); +server.listen(common.PORT); + +server.on('listening', function() { + net.createConnection(common.PORT).on('connect', function() { + this.destroy(); + }).on('close', function() { + server.close(); + }); +}); diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js new file mode 100644 index 000000000..1501d944a --- /dev/null +++ b/test/parallel/test-http-exceptions.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + intentionally_not_defined(); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Thank you, come again.'); + res.end(); +}); + +server.listen(common.PORT, function() { + var req; + for (var i = 0; i < 4; i += 1) { + req = http.get({ port: common.PORT, path: '/busy/' + i }); + } +}); + +var exception_count = 0; + +process.on('uncaughtException', function(err) { + console.log('Caught an exception: ' + err); + if (err.name === 'AssertionError') throw err; + if (++exception_count == 4) process.exit(0); +}); + diff --git a/test/parallel/test-http-exit-delay.js b/test/parallel/test-http-exit-delay.js new file mode 100644 index 000000000..900f4fabd --- /dev/null +++ b/test/parallel/test-http-exit-delay.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common.js'); +var http = require('http'); + +var start; +var server = http.createServer(function(req, res) { + req.resume(); + req.on('end', function() { + res.end('Success'); + }); + + server.close(); +}); + +server.listen(common.PORT, 'localhost', function() { + var interval_id = setInterval(function() { + start = new Date(); + if (start.getMilliseconds() > 100) + return; + + console.log(start.toISOString()); + var req = http.request({ + 'host': 'localhost', + 'port': common.PORT, + 'agent': false, + 'method': 'PUT' + }); + + req.end('Test'); + clearInterval(interval_id); + }, 10); +}); + +process.on('exit', function() { + var end = new Date(); + console.log(end.toISOString()); + assert.equal(start.getSeconds(), end.getSeconds()); + assert(end.getMilliseconds() < 900); + console.log('ok'); +}); diff --git a/test/parallel/test-http-expect-continue.js b/test/parallel/test-http-expect-continue.js new file mode 100644 index 000000000..54c04cce0 --- /dev/null +++ b/test/parallel/test-http-expect-continue.js @@ -0,0 +1,88 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var outstanding_reqs = 0; +var test_req_body = 'some stuff...\n'; +var test_res_body = 'other stuff!\n'; +var sent_continue = false; +var got_continue = false; + +function handler(req, res) { + assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); + common.debug('Server sending full response...'); + res.writeHead(200, { + 'Content-Type' : 'text/plain', + 'ABCD' : '1' + }); + res.end(test_res_body); +} + +var server = http.createServer(handler); +server.on('checkContinue', function(req, res) { + common.debug('Server got Expect: 100-continue...'); + res.writeContinue(); + sent_continue = true; + setTimeout(function() { + handler(req, res); + }, 100); +}); +server.listen(common.PORT); + + + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/world', + headers: { 'Expect': '100-continue' } + }); + common.debug('Client sending request...'); + outstanding_reqs++; + var body = ''; + req.on('continue', function() { + common.debug('Client got 100 Continue...'); + got_continue = true; + req.end(test_req_body); + }); + req.on('response', function(res) { + assert.equal(got_continue, true, + 'Full response received before 100 Continue'); + assert.equal(200, res.statusCode, + 'Final status code was ' + res.statusCode + ', not 200.'); + res.setEncoding('utf8'); + res.on('data', function(chunk) { body += chunk; }); + res.on('end', function() { + common.debug('Got full response.'); + assert.equal(body, test_res_body, 'Response body doesn\'t match.'); + assert.ok('abcd' in res.headers, 'Response headers missing.'); + outstanding_reqs--; + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + }); + }); +}); diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js new file mode 100644 index 000000000..1649a6a92 --- /dev/null +++ b/test/parallel/test-http-extra-response.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +// If an HTTP server is broken and sends data after the end of the response, +// node should ignore it and drop the connection. +// Demos this bug: https://github.com/joyent/node/issues/680 + +var body = 'hello world\r\n'; +var fullResponse = + 'HTTP/1.1 500 Internal Server Error\r\n' + + 'Content-Length: ' + body.length + '\r\n' + + 'Content-Type: text/plain\r\n' + + 'Date: Fri + 18 Feb 2011 06:22:45 GMT\r\n' + + 'Host: 10.20.149.2\r\n' + + 'Access-Control-Allow-Credentials: true\r\n' + + 'Server: badly broken/0.1 (OS NAME)\r\n' + + '\r\n' + + body; + +var gotResponse = false; + + +var server = net.createServer(function(socket) { + var postBody = ''; + + socket.setEncoding('utf8'); + + socket.on('data', function(chunk) { + postBody += chunk; + + if (postBody.indexOf('\r\n') > -1) { + socket.write(fullResponse); + // omg, I wrote the response twice, what a terrible HTTP server I am. + socket.end(fullResponse); + } + }); +}); + + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + var buffer = ''; + console.log('Got res code: ' + res.statusCode); + + res.setEncoding('utf8'); + res.on('data', function(chunk) { + buffer += chunk; + }); + + res.on('end', function() { + console.log('Response ended, read ' + buffer.length + ' bytes'); + assert.equal(body, buffer); + server.close(); + gotResponse = true; + }); + }); +}); + + +process.on('exit', function() { + assert.ok(gotResponse); +}); + diff --git a/test/parallel/test-http-flush.js b/test/parallel/test-http-flush.js new file mode 100644 index 000000000..842cf8729 --- /dev/null +++ b/test/parallel/test-http-flush.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +http.createServer(function(req, res) { + res.end('ok'); + this.close(); +}).listen(common.PORT, '127.0.0.1', function() { + var req = http.request({ + method: 'POST', + host: '127.0.0.1', + port: common.PORT, + }); + req.flush(); // Flush the request headers. + req.flush(); // Should be idempotent. +}); diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js new file mode 100644 index 000000000..d33df8b88 --- /dev/null +++ b/test/parallel/test-http-full-response.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +// This test requires the program 'ab' +var http = require('http'); +var exec = require('child_process').exec; + +var bodyLength = 12345; + +var body = ''; +for (var i = 0; i < bodyLength; i++) { + body += 'c'; +} + +var server = http.createServer(function(req, res) { + res.writeHead(200, { + 'Content-Length': bodyLength, + 'Content-Type': 'text/plain' + }); + res.end(body); +}); + +var runs = 0; + +function runAb(opts, callback) { + var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; + exec(command, function(err, stdout, stderr) { + if (err) { + if (/ab|apr/mi.test(stderr)) { + console.log('problem spawning ab - skipping test.\n' + stderr); + process.reallyExit(0); + } + process.exit(); + return; + } + + var m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); + var documentLength = parseInt(m[1]); + + var m = /Complete requests:\s*(\d+)/mi.exec(stdout); + var completeRequests = parseInt(m[1]); + + var m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); + var htmlTransfered = parseInt(m[1]); + + assert.equal(bodyLength, documentLength); + assert.equal(completeRequests * documentLength, htmlTransfered); + + runs++; + + if (callback) callback(); + }); +} + +server.listen(common.PORT, function() { + runAb('-c 1 -n 10', function() { + console.log('-c 1 -n 10 okay'); + + runAb('-c 1 -n 100', function() { + console.log('-c 1 -n 100 okay'); + + runAb('-c 1 -n 1000', function() { + console.log('-c 1 -n 1000 okay'); + server.close(); + }); + }); + }); + +}); + +process.on('exit', function() { + assert.equal(3, runs); +}); diff --git a/test/parallel/test-http-get-pipeline-problem.js b/test/parallel/test-http-get-pipeline-problem.js new file mode 100644 index 000000000..720ce4b89 --- /dev/null +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -0,0 +1,111 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// We are demonstrating a problem with http.get when queueing up many +// transfers. The server simply introduces some delay and sends a file. +// Note this is demonstrated with connection: close. +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var fs = require('fs'); + +var image = fs.readFileSync(common.fixturesDir + '/person.jpg'); + +console.log('image.length = ' + image.length); + +var total = 100; +var requests = 0, responses = 0; + +var server = http.Server(function(req, res) { + if (++requests == total) { + server.close(); + } + + setTimeout(function() { + res.writeHead(200, { + 'content-type': 'image/jpeg', + 'connection': 'close', + 'content-length': image.length + }); + res.end(image); + }, 1); +}); + + +server.listen(common.PORT, function() { + for (var i = 0; i < total; i++) { + (function() { + var x = i; + + var opts = { + port: common.PORT, + headers: { connection: 'close' } + }; + + http.get(opts, function(res) { + console.error('recv ' + x); + var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); + res.pipe(s); + + // TODO there should be a callback to pipe() that will allow + // us to get a callback when the pipe is finished. + res.on('end', function() { + console.error('done ' + x); + if (++responses == total) { + s.on('close', checkFiles); + } + }); + }).on('error', function(e) { + console.error('error! ', e.message); + throw e; + }); + })(); + } +}); + + +var checkedFiles = false; +function checkFiles() { + // Should see 1.jpg, 2.jpg, ..., 100.jpg in tmpDir + var files = fs.readdirSync(common.tmpDir); + assert(total <= files.length); + + for (var i = 0; i < total; i++) { + var fn = i + '.jpg'; + assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); + var stat = fs.statSync(common.tmpDir + '/' + fn); + assert.equal(image.length, stat.size, + "size doesn't match on '" + fn + + "'. Got " + stat.size + ' bytes'); + } + + checkedFiles = true; +} + + +process.on('exit', function() { + assert.equal(total, requests); + assert.equal(total, responses); + assert.ok(checkedFiles); +}); diff --git a/test/parallel/test-http-head-request.js b/test/parallel/test-http-head-request.js new file mode 100644 index 000000000..ca0f13a1a --- /dev/null +++ b/test/parallel/test-http-head-request.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + + +var body = 'hello world\n'; +var id = 0; + +function test(headers) { + var port = common.PORT + id++; + + var server = http.createServer(function(req, res) { + console.error('req: %s headers: %j', req.method, headers); + res.writeHead(200, headers); + res.end(); + server.close(); + }); + + var gotEnd = false; + + server.listen(port, function() { + var request = http.request({ + port: port, + method: 'HEAD', + path: '/' + }, function(response) { + console.error('response start'); + response.on('end', function() { + console.error('response end'); + gotEnd = true; + }); + response.resume(); + }); + request.end(); + }); + + process.on('exit', function() { + assert.ok(gotEnd); + }); +} + +test({ + 'Transfer-Encoding': 'chunked' +}); +test({ + 'Content-Length': body.length +}); diff --git a/test/parallel/test-http-head-response-has-no-body-end.js b/test/parallel/test-http-head-response-has-no-body-end.js new file mode 100644 index 000000000..cde777a58 --- /dev/null +++ b/test/parallel/test-http-head-response-has-no-body-end.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +// This test is to make sure that when the HTTP server +// responds to a HEAD request with data to res.end, +// it does not send any body. + +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.end('FAIL'); // broken: sends FAIL from hot path. +}); +server.listen(common.PORT); + +var responseComplete = false; + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'HEAD', + path: '/' + }, function(res) { + common.error('response'); + res.on('end', function() { + common.error('response end'); + server.close(); + responseComplete = true; + }); + res.resume(); + }); + common.error('req'); + req.end(); +}); + +process.on('exit', function() { + assert.ok(responseComplete); +}); diff --git a/test/parallel/test-http-head-response-has-no-body.js b/test/parallel/test-http-head-response-has-no-body.js new file mode 100644 index 000000000..ab6bd5b51 --- /dev/null +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +// This test is to make sure that when the HTTP server +// responds to a HEAD request, it does not send any body. +// In this case it was sending '0\r\n\r\n' + +var server = http.createServer(function(req, res) { + res.writeHead(200); // broken: defaults to TE chunked + res.end(); +}); +server.listen(common.PORT); + +var responseComplete = false; + +server.on('listening', function() { + var req = http.request({ + port: common.PORT, + method: 'HEAD', + path: '/' + }, function(res) { + common.error('response'); + res.on('end', function() { + common.error('response end'); + server.close(); + responseComplete = true; + }); + res.resume(); + }); + common.error('req'); + req.end(); +}); + +process.on('exit', function() { + assert.ok(responseComplete); +}); diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js new file mode 100644 index 000000000..338377592 --- /dev/null +++ b/test/parallel/test-http-header-read.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Verify that ServerResponse.getHeader() works correctly even after +// the response header has been sent. Issue 752 on github. + +var s = http.createServer(function(req, res) { + var contentType = 'Content-Type'; + var plain = 'text/plain'; + res.setHeader(contentType, plain); + assert.ok(!res.headersSent); + res.writeHead(200); + assert.ok(res.headersSent); + res.end('hello world\n'); + // This checks that after the headers have been sent, getHeader works + // and does not throw an exception (Issue 752) + assert.doesNotThrow( + function() { + assert.equal(plain, res.getHeader(contentType)); + } + ); +}); + +s.listen(common.PORT, runTest); + +function runTest() { + http.get({ port: common.PORT }, function(response) { + response.on('end', function() { + s.close(); + }); + response.resume(); + }); +} diff --git a/test/parallel/test-http-header-response-splitting.js b/test/parallel/test-http-header-response-splitting.js new file mode 100644 index 000000000..1d3a85ce8 --- /dev/null +++ b/test/parallel/test-http-header-response-splitting.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + http = require('http'); + +var testIndex = 0, + responses = 0; + +var server = http.createServer(function(req, res) { + switch (testIndex++) { + case 0: + res.writeHead(200, { test: 'foo \r\ninvalid: bar' }); + break; + case 1: + res.writeHead(200, { test: 'foo \ninvalid: bar' }); + break; + case 2: + res.writeHead(200, { test: 'foo \rinvalid: bar' }); + break; + case 3: + res.writeHead(200, { test: 'foo \n\n\ninvalid: bar' }); + break; + case 4: + res.writeHead(200, { test: 'foo \r\n \r\n \r\ninvalid: bar' }); + server.close(); + break; + default: + assert(false); + } + res.end('Hi mars!'); +}); + +server.listen(common.PORT, function() { + for (var i = 0; i < 5; i++) { + var req = http.get({ port: common.PORT, path: '/' }, function(res) { + assert.strictEqual(res.headers.test, 'foo invalid: bar'); + assert.strictEqual(res.headers.invalid, undefined); + responses++; + res.resume(); + }); + } +}); + +process.on('exit', function() { + assert.strictEqual(responses, 5); +}); diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js new file mode 100644 index 000000000..21a93df53 --- /dev/null +++ b/test/parallel/test-http-hex-write.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var expect = 'hex\nutf8\n'; +var data = ''; +var ended = false; + +process.on('exit', function() { + assert(ended); + assert.equal(data, expect); + console.log('ok'); +}); + +http.createServer(function(q, s) { + s.setHeader('content-length', expect.length); + s.write('6865780a', 'hex'); + s.write('utf8\n'); + s.end(); + this.close(); +}).listen(common.PORT, function() { + http.request({ port: common.PORT }).on('response', function(res) { + res.setEncoding('ascii'); + res.on('data', function(c) { + data += c; + }); + res.on('end', function() { + ended = true; + }); + }).end(); +}); diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js new file mode 100644 index 000000000..ca7f70947 --- /dev/null +++ b/test/parallel/test-http-host-headers.js @@ -0,0 +1,195 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var http = require('http'), + https = require('https'), + fs = require('fs'), + common = require('../common'), + assert = require('assert'), + options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') + }, + httpServer = http.createServer(reqHandler), + httpsServer = https.createServer(options, reqHandler); + +function reqHandler(req, res) { + console.log('Got request: ' + req.headers.host + ' ' + req.url); + if (req.url === '/setHostFalse5') { + assert.equal(req.headers.host, undefined); + } else { + assert.equal(req.headers.host, 'localhost:' + common.PORT, + 'Wrong host header for req[' + req.url + ']: ' + + req.headers.host); + } + res.writeHead(200, {}); + //process.nextTick(function() { res.end('ok'); }); + res.end('ok'); +} + +function thrower(er) { + throw er; +} + +testHttp(); + +function testHttp() { + + console.log('testing http on port ' + common.PORT); + + var counter = 0; + + function cb(res) { + counter--; + console.log('back from http request. counter = ' + counter); + if (counter === 0) { + httpServer.close(); + testHttps(); + } + res.resume(); + } + + httpServer.listen(common.PORT, function(er) { + console.error('listening on ' + common.PORT); + + if (er) throw er; + + http.get({ + method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower); + + http.request({ + method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + http.request({ + method: 'POST', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + http.request({ + method: 'PUT', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + http.request({ + method: 'DELETE', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + }); +} + +function testHttps() { + + console.log('testing https on port ' + common.PORT); + + var counter = 0; + + function cb(res) { + counter--; + console.log('back from https request. counter = ' + counter); + if (counter === 0) { + httpsServer.close(); + console.log('ok'); + } + res.resume(); + } + + httpsServer.listen(common.PORT, function(er) { + if (er) throw er; + + https.get({ + method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower); + + https.request({ + method: 'GET', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + https.request({ + method: 'POST', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + https.request({ + method: 'PUT', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + https.request({ + method: 'DELETE', + path: '/' + (counter++), + host: 'localhost', + //agent: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + + https.get({ + method: 'GET', + path: '/setHostFalse' + (counter++), + host: 'localhost', + setHost: false, + port: common.PORT, + rejectUnauthorized: false + }, cb).on('error', thrower).end(); + }); +} diff --git a/test/parallel/test-http-incoming-pipelined-socket-destroy.js b/test/parallel/test-http-incoming-pipelined-socket-destroy.js new file mode 100644 index 000000000..3a2f531a7 --- /dev/null +++ b/test/parallel/test-http-incoming-pipelined-socket-destroy.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + + +// Set up some timing issues where sockets can be destroyed +// via either the req or res. +var server = http.createServer(function(req, res) { + switch (req.url) { + case '/1': + return setTimeout(function() { + req.socket.destroy(); + server.emit('requestDone'); + }); + + case '/2': + return process.nextTick(function() { + res.destroy(); + server.emit('requestDone'); + }); + + // in one case, actually send a response in 2 chunks + case '/3': + res.write('hello '); + return setTimeout(function() { + res.end('world!'); + server.emit('requestDone'); + }); + + default: + res.destroy(); + server.emit('requestDone'); + } +}); + + +// Make a bunch of requests pipelined on the same socket +function generator(seeds) { + return seeds.map(function(r) { + return 'GET /' + r + ' HTTP/1.1\r\n' + + 'Host: localhost:' + common.PORT + '\r\n' + + '\r\n' + + '\r\n' + }).join(''); +} + + +server.listen(common.PORT, function() { + var seeds = [ 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ]; + var client = net.connect({ port: common.PORT }); + var done = 0; + server.on('requestDone', function() { + if (++done == seeds.length) { + server.close(); + } + }); + + // immediately write the pipelined requests. + // Some of these will not have a socket to destroy! + client.write(generator(seeds)); +}); + +process.on('exit', function(c) { + if (!c) + console.log('ok'); +}); diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js new file mode 100644 index 000000000..4318bd970 --- /dev/null +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +var body = 'hello world\n'; +var headers = {'connection': 'keep-alive'}; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); + res.write(body); + res.end(); +}); + +var connectCount = 0; + + +server.listen(common.PORT, function() { + var agent = new http.Agent({ maxSockets: 1 }); + var name = agent.getName({ port: common.PORT }); + var request = http.request({ + method: 'GET', + path: '/', + headers: headers, + port: common.PORT, + agent: agent + }, function(res) { + assert.equal(1, agent.sockets[name].length); + res.resume(); + }); + request.on('socket', function(s) { + s.on('connect', function() { + connectCount++; + }); + }); + request.end(); + + request = http.request({ + method: 'GET', + path: '/', + headers: headers, + port: common.PORT, + agent: agent + }, function(res) { + assert.equal(1, agent.sockets[name].length); + res.resume(); + }); + request.on('socket', function(s) { + s.on('connect', function() { + connectCount++; + }); + }); + request.end(); + request = http.request({ + method: 'GET', + path: '/', + headers: headers, + port: common.PORT, + agent: agent + }, function(response) { + response.on('end', function() { + assert.equal(1, agent.sockets[name].length); + server.close(); + }); + response.resume(); + }); + request.on('socket', function(s) { + s.on('connect', function() { + connectCount++; + }); + }); + request.end(); +}); + +process.on('exit', function() { + assert.equal(3, connectCount); +}); diff --git a/test/parallel/test-http-keep-alive.js b/test/parallel/test-http-keep-alive.js new file mode 100644 index 000000000..75049c9c6 --- /dev/null +++ b/test/parallel/test-http-keep-alive.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var body = 'hello world\n'; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': body.length}); + res.write(body); + res.end(); +}); + +var connectCount = 0; +var agent = new http.Agent({maxSockets: 1}); +var headers = {'connection': 'keep-alive'}; +var name = agent.getName({ port: common.PORT }); + +server.listen(common.PORT, function() { + http.get({ + path: '/', headers: headers, port: common.PORT, agent: agent + }, function(response) { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.requests[name].length, 2); + response.resume(); + }); + + http.get({ + path: '/', headers: headers, port: common.PORT, agent: agent + }, function(response) { + assert.equal(agent.sockets[name].length, 1); + assert.equal(agent.requests[name].length, 1); + response.resume(); + }); + + http.get({ + path: '/', headers: headers, port: common.PORT, agent: agent + }, function(response) { + response.on('end', function() { + assert.equal(agent.sockets[name].length, 1); + assert(!agent.requests.hasOwnProperty(name)); + server.close(); + }); + response.resume(); + }); +}); + +process.on('exit', function() { + assert(!agent.sockets.hasOwnProperty(name)); + assert(!agent.requests.hasOwnProperty(name)); +}); diff --git a/test/parallel/test-http-keepalive-client.js b/test/parallel/test-http-keepalive-client.js new file mode 100644 index 000000000..177a8ed7a --- /dev/null +++ b/test/parallel/test-http-keepalive-client.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + + +var serverSocket = null; +var server = http.createServer(function(req, res) { + // They should all come in on the same server socket. + if (serverSocket) { + assert.equal(req.socket, serverSocket); + } else { + serverSocket = req.socket; + } + + res.end(req.url); +}); +server.listen(common.PORT); + +var agent = http.Agent({ keepAlive: true }); + + +var clientSocket = null; +var expectRequests = 10; +var actualRequests = 0; + + +makeRequest(expectRequests); +function makeRequest(n) { + if (n === 0) { + server.close(); + agent.destroy(); + return; + } + + var req = http.request({ + port: common.PORT, + agent: agent, + path: '/' + n + }); + + req.end(); + + req.on('socket', function(sock) { + if (clientSocket) { + assert.equal(sock, clientSocket); + } else { + clientSocket = sock; + } + }); + + req.on('response', function(res) { + var data = ''; + res.setEncoding('utf8'); + res.on('data', function(c) { + data += c; + }); + res.on('end', function() { + assert.equal(data, '/' + n); + setTimeout(function() { + actualRequests++; + makeRequest(n - 1); + }, 1); + }); + }); +} + +process.on('exit', function() { + assert.equal(actualRequests, expectRequests) + console.log('ok'); +}); diff --git a/test/parallel/test-http-keepalive-maxsockets.js b/test/parallel/test-http-keepalive-maxsockets.js new file mode 100644 index 000000000..8481eec35 --- /dev/null +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + + +var serverSockets = []; +var server = http.createServer(function(req, res) { + if (serverSockets.indexOf(req.socket) === -1) { + serverSockets.push(req.socket); + } + res.end(req.url); +}); +server.listen(common.PORT); + +var agent = http.Agent({ + keepAlive: true, + maxSockets: 5, + maxFreeSockets: 2 +}); + +// make 10 requests in parallel, +// then 10 more when they all finish. +function makeReqs(n, cb) { + for (var i = 0; i < n; i++) + makeReq(i, then); + + function then(er) { + if (er) + return cb(er); + else if (--n === 0) + setTimeout(cb, 100); + } +} + +function makeReq(i, cb) { + http.request({ + port: common.PORT, + path: '/' + i, + agent: agent + }, function(res) { + var data = ''; + res.setEncoding('ascii'); + res.on('data', function(c) { + data += c; + }); + res.on('end', function() { + assert.equal(data, '/' + i); + cb(); + }); + }).end(); +} + +var closed = false; +makeReqs(10, function(er) { + assert.ifError(er); + assert.equal(count(agent.freeSockets), 2); + assert.equal(count(agent.sockets), 0); + assert.equal(serverSockets.length, 5); + + // now make 10 more reqs. + // should use the 2 free reqs from the pool first. + makeReqs(10, function(er) { + assert.ifError(er); + assert.equal(count(agent.freeSockets), 2); + assert.equal(count(agent.sockets), 0); + assert.equal(serverSockets.length, 8); + + agent.destroy(); + server.close(function() { + closed = true; + }); + }); +}); + +function count(sockets) { + return Object.keys(sockets).reduce(function(n, name) { + return n + sockets[name].length; + }, 0); +} + +process.on('exit', function() { + assert(closed); + console.log('ok'); +}); diff --git a/test/parallel/test-http-keepalive-request.js b/test/parallel/test-http-keepalive-request.js new file mode 100644 index 000000000..3b8737540 --- /dev/null +++ b/test/parallel/test-http-keepalive-request.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + + +var serverSocket = null; +var server = http.createServer(function(req, res) { + // They should all come in on the same server socket. + if (serverSocket) { + assert.equal(req.socket, serverSocket); + } else { + serverSocket = req.socket; + } + + res.end(req.url); +}); +server.listen(common.PORT); + +var agent = http.Agent({ keepAlive: true }); + + +var clientSocket = null; +var expectRequests = 10; +var actualRequests = 0; + + +makeRequest(expectRequests); +function makeRequest(n) { + if (n === 0) { + server.close(); + agent.destroy(); + return; + } + + var req = http.request({ + port: common.PORT, + path: '/' + n, + agent: agent + }); + + req.end(); + + req.on('socket', function(sock) { + if (clientSocket) { + assert.equal(sock, clientSocket); + } else { + clientSocket = sock; + } + }); + + req.on('response', function(res) { + var data = ''; + res.setEncoding('utf8'); + res.on('data', function(c) { + data += c; + }); + res.on('end', function() { + assert.equal(data, '/' + n); + setTimeout(function() { + actualRequests++; + makeRequest(n - 1); + }, 1); + }); + }); +} + +process.on('exit', function() { + assert.equal(actualRequests, expectRequests) + console.log('ok'); +}); diff --git a/test/parallel/test-http-legacy.js b/test/parallel/test-http-legacy.js new file mode 100644 index 000000000..c6605b0e4 --- /dev/null +++ b/test/parallel/test-http-legacy.js @@ -0,0 +1,105 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +function p(x) { + common.error(common.inspect(x)); +} + +var responses_sent = 0; +var responses_recvd = 0; +var body0 = ''; +var body1 = ''; + +var server = http.createServer(function(req, res) { + if (responses_sent == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + + console.dir(req.headers); + assert.equal(true, 'accept' in req.headers); + assert.equal('*/*', req.headers['accept']); + + assert.equal(true, 'foo' in req.headers); + assert.equal('bar', req.headers['foo']); + } + + if (responses_sent == 1) { + assert.equal('POST', req.method); + assert.equal('/world', url.parse(req.url).pathname); + this.close(); + } + + req.on('end', function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('The path was ' + url.parse(req.url).pathname); + res.end(); + responses_sent += 1; + }); + req.resume(); + + //assert.equal('127.0.0.1', res.connection.remoteAddress); +}); + +server.listen(common.PORT, function() { + var client = http.createClient(common.PORT); + var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); + setTimeout(function() { + req.end(); + }, 100); + req.on('response', function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body0 += chunk; }); + common.debug('Got /hello response'); + }); + + setTimeout(function() { + var req = client.request('POST', '/world'); + req.end(); + req.on('response', function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body1 += chunk; }); + common.debug('Got /world response'); + }); + }, 1); +}); + +process.on('exit', function() { + common.debug('responses_recvd: ' + responses_recvd); + assert.equal(2, responses_recvd); + + common.debug('responses_sent: ' + responses_sent); + assert.equal(2, responses_sent); + + assert.equal('The path was /hello', body0); + assert.equal('The path was /world', body1); +}); diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js new file mode 100644 index 000000000..719525cc6 --- /dev/null +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var invalidLocalAddress = '1.2.3.4'; +var gotError = false; + +var server = http.createServer(function(req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); + req.resume(); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var req = http.request({ + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: invalidLocalAddress + }, function(res) { + assert.fail('unexpectedly got response from server'); + }).on('error', function(e) { + console.log('client got error: ' + e.message); + gotError = true; + server.close(); + }).end(); +}); + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js new file mode 100644 index 000000000..d5778e09b --- /dev/null +++ b/test/parallel/test-http-localaddress.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'), + assert = require('assert'); + +if (['linux', 'win32'].indexOf(process.platform) == -1) { + console.log('Skipping platform-specific test.'); + process.exit(); +} + +var server = http.createServer(function (req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + assert.equal('127.0.0.2', req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); + req.resume(); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var options = { host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: '127.0.0.2' }; + + var req = http.request(options, function(res) { + res.on('end', function() { + server.close(); + process.exit(); + }); + res.resume(); + }); + req.end(); +}); diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js new file mode 100644 index 000000000..52165a21d --- /dev/null +++ b/test/parallel/test-http-malformed-request.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); +var url = require('url'); + +// Make sure no exceptions are thrown when receiving malformed HTTP +// requests. + +var nrequests_completed = 0; +var nrequests_expected = 1; + +var server = http.createServer(function(req, res) { + console.log('req: ' + JSON.stringify(url.parse(req.url))); + + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('Hello World'); + res.end(); + + if (++nrequests_completed == nrequests_expected) server.close(); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var c = net.createConnection(common.PORT); + c.on('connect', function() { + c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); + c.end(); + }); + + // TODO add more! +}); + +process.on('exit', function() { + assert.equal(nrequests_expected, nrequests_completed); +}); diff --git a/test/parallel/test-http-many-ended-pipelines.js b/test/parallel/test-http-many-ended-pipelines.js new file mode 100644 index 000000000..dffde722f --- /dev/null +++ b/test/parallel/test-http-many-ended-pipelines.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// no warnings should happen! +var trace = console.trace; +console.trace = function() { + trace.apply(console, arguments); + throw new Error('no tracing should happen here'); +}; + +var http = require('http'); +var net = require('net'); + +var numRequests = 20; +var done = 0; + +var server = http.createServer(function(req, res) { + res.end('ok'); + + // Oh no! The connection died! + req.socket.destroy(); + if (++done == numRequests) + server.close(); +}); + +server.listen(common.PORT); + +var client = net.connect({ port: common.PORT, allowHalfOpen: true }); +for (var i = 0; i < numRequests; i++) { + client.write('GET / HTTP/1.1\r\n' + + 'Host: some.host.name\r\n'+ + '\r\n\r\n'); +} +client.end(); +client.pipe(process.stdout); diff --git a/test/parallel/test-http-max-headers-count.js b/test/parallel/test-http-max-headers-count.js new file mode 100644 index 000000000..4595b11e7 --- /dev/null +++ b/test/parallel/test-http-max-headers-count.js @@ -0,0 +1,88 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var requests = 0; +var responses = 0; + +var headers = {}; +var N = 2000; +for (var i = 0; i < N; ++i) { + headers['key' + i] = i; +} + +var maxAndExpected = [ // for server + [50, 50], + [1500, 1500], + [0, N + 2] // Host and Connection +]; +var max = maxAndExpected[requests][0]; +var expected = maxAndExpected[requests][1]; + +var server = http.createServer(function(req, res) { + assert.equal(Object.keys(req.headers).length, expected); + if (++requests < maxAndExpected.length) { + max = maxAndExpected[requests][0]; + expected = maxAndExpected[requests][1]; + server.maxHeadersCount = max; + } + res.writeHead(200, headers); + res.end(); +}); +server.maxHeadersCount = max; + +server.listen(common.PORT, function() { + var maxAndExpected = [ // for client + [20, 20], + [1200, 1200], + [0, N + 3] // Connection, Date and Transfer-Encoding + ]; + doRequest(); + + function doRequest() { + var max = maxAndExpected[responses][0]; + var expected = maxAndExpected[responses][1]; + var req = http.request({ + port: common.PORT, + headers: headers + }, function(res) { + assert.equal(Object.keys(res.headers).length, expected); + res.on('end', function() { + if (++responses < maxAndExpected.length) { + doRequest(); + } else { + server.close(); + } + }); + res.resume(); + }); + req.maxHeadersCount = max; + req.end(); + } +}); + +process.on('exit', function() { + assert.equal(requests, maxAndExpected.length); + assert.equal(responses, maxAndExpected.length); +}); diff --git a/test/parallel/test-http-methods.js b/test/parallel/test-http-methods.js new file mode 100644 index 000000000..eec66d280 --- /dev/null +++ b/test/parallel/test-http-methods.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); + +assert(Array.isArray(http.METHODS)); +assert(http.METHODS.length > 0); +assert(http.METHODS.indexOf('GET') !== -1); +assert(http.METHODS.indexOf('HEAD') !== -1); +assert(http.METHODS.indexOf('POST') !== -1); +assert.deepEqual(util._extend([], http.METHODS), http.METHODS.sort()); diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js new file mode 100644 index 000000000..9415abadc --- /dev/null +++ b/test/parallel/test-http-multi-line-headers.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +var gotResponse = false; + +var server = net.createServer(function(conn) { + var body = 'Yet another node.js server.'; + + var response = + 'HTTP/1.1 200 OK\r\n' + + 'Connection: close\r\n' + + 'Content-Length: ' + body.length + '\r\n' + + 'Content-Type: text/plain;\r\n' + + ' x-unix-mode=0600;\r\n' + + ' name=\"hello.txt\"\r\n' + + '\r\n' + + body; + + conn.end(response); + server.close(); +}); + +server.listen(common.PORT, function() { + http.get({host: '127.0.0.1', port: common.PORT}, function(res) { + assert.equal(res.headers['content-type'], + 'text/plain; x-unix-mode=0600; name="hello.txt"'); + gotResponse = true; + res.destroy(); + }); +}); + +process.on('exit', function() { + assert.ok(gotResponse); +}); diff --git a/test/parallel/test-http-mutable-headers.js b/test/parallel/test-http-mutable-headers.js new file mode 100644 index 000000000..6106ac6ee --- /dev/null +++ b/test/parallel/test-http-mutable-headers.js @@ -0,0 +1,153 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Simple test of Node's HTTP Client mutable headers +// OutgoingMessage.prototype.setHeader(name, value) +// OutgoingMessage.prototype.getHeader(name) +// OutgoingMessage.prototype.removeHeader(name, value) +// ServerResponse.prototype.statusCode +// .method +// .path + +var testsComplete = 0; +var test = 'headers'; +var content = 'hello world\n'; +var cookies = [ + 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', + 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' +]; + +var s = http.createServer(function(req, res) { + switch (test) { + case 'headers': + assert.throws(function() { res.setHeader() }); + assert.throws(function() { res.setHeader('someHeader') }); + assert.throws(function() { res.getHeader() }); + assert.throws(function() { res.removeHeader() }); + + res.setHeader('x-test-header', 'testing'); + res.setHeader('X-TEST-HEADER2', 'testing'); + res.setHeader('set-cookie', cookies); + res.setHeader('x-test-array-header', [1, 2, 3]); + + var val1 = res.getHeader('x-test-header'); + var val2 = res.getHeader('x-test-header2'); + assert.equal(val1, 'testing'); + assert.equal(val2, 'testing'); + + res.removeHeader('x-test-header2'); + break; + + case 'contentLength': + res.setHeader('content-length', content.length); + assert.equal(content.length, res.getHeader('Content-Length')); + break; + + case 'transferEncoding': + res.setHeader('transfer-encoding', 'chunked'); + assert.equal(res.getHeader('Transfer-Encoding'), 'chunked'); + break; + + case 'writeHead': + res.statusCode = 404; + res.setHeader('x-foo', 'keyboard cat'); + res.writeHead(200, { 'x-foo': 'bar', 'x-bar': 'baz' }); + break; + } + + res.statusCode = 201; + res.end(content); +}); + +s.listen(common.PORT, nextTest); + + +function nextTest() { + if (test === 'end') { + return s.close(); + } + + var bufferedResponse = ''; + + http.get({ port: common.PORT }, function(response) { + console.log('TEST: ' + test); + console.log('STATUS: ' + response.statusCode); + console.log('HEADERS: '); + console.dir(response.headers); + + switch (test) { + case 'headers': + assert.equal(response.statusCode, 201); + assert.equal(response.headers['x-test-header'], + 'testing'); + assert.equal(response.headers['x-test-array-header'], + [1, 2, 3].join(', ')); + assert.deepEqual(cookies, + response.headers['set-cookie']); + assert.equal(response.headers['x-test-header2'] !== undefined, false); + // Make the next request + test = 'contentLength'; + console.log('foobar'); + break; + + case 'contentLength': + assert.equal(response.headers['content-length'], content.length); + test = 'transferEncoding'; + break; + + case 'transferEncoding': + assert.equal(response.headers['transfer-encoding'], 'chunked'); + test = 'writeHead'; + break; + + case 'writeHead': + assert.equal(response.headers['x-foo'], 'bar'); + assert.equal(response.headers['x-bar'], 'baz'); + assert.equal(200, response.statusCode); + test = 'end'; + break; + + default: + throw Error('?'); + } + + response.setEncoding('utf8'); + response.on('data', function(s) { + bufferedResponse += s; + }); + + response.on('end', function() { + assert.equal(content, bufferedResponse); + testsComplete++; + nextTest(); + }); + }); +} + + +process.on('exit', function() { + assert.equal(4, testsComplete); +}); + diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js new file mode 100644 index 000000000..8c565aedc --- /dev/null +++ b/test/parallel/test-http-no-content-length.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +var body = ''; + +var server = net.createServer(function(socket) { + // Neither Content-Length nor Connection + socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); +}).listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + res.setEncoding('utf8'); + res.on('data', function(chunk) { + body += chunk; + }); + res.on('end', function() { + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(body, 'Hello'); +}); diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js new file mode 100644 index 000000000..668040a81 --- /dev/null +++ b/test/parallel/test-http-outgoing-finish.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +http.createServer(function(req, res) { + req.resume(); + req.on('end', function() { + write(res); + }); + this.close(); +}).listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + method: 'PUT' + }); + write(req); + req.on('response', function(res) { + res.resume(); + }); +}); + +var buf = new Buffer(1024 * 16); +buf.fill('x'); +function write(out) { + var name = out.constructor.name; + var finishEvent = false; + var endCb = false; + + // first, write until it gets some backpressure + while (out.write(buf)) {} + + // now end, and make sure that we don't get the 'finish' event + // before the tick where the cb gets called. We give it until + // nextTick because this is added as a listener before the endcb + // is registered. The order is not what we're testing here, just + // that 'finish' isn't emitted until the stream is fully flushed. + out.on('finish', function() { + finishEvent = true; + console.error('%s finish event', name); + process.nextTick(function() { + assert(endCb, name + ' got finish event before endcb!'); + console.log('ok - %s finishEvent', name); + }); + }); + + out.end(buf, function() { + endCb = true; + console.error('%s endCb', name); + process.nextTick(function() { + assert(finishEvent, name + ' got endCb event before finishEvent!'); + console.log('ok - %s endCb', name); + }); + }); +} diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js new file mode 100644 index 000000000..0e2a77bb3 --- /dev/null +++ b/test/parallel/test-http-parser-bad-ref.js @@ -0,0 +1,86 @@ +// Run this program with valgrind or efence with --expose_gc to expose the +// problem. + +// Flags: --expose_gc + +var common = require('../common'); +var assert = require('assert'); +var HTTPParser = process.binding('http_parser').HTTPParser; + +var kOnHeaders = HTTPParser.kOnHeaders | 0; +var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; +var kOnBody = HTTPParser.kOnBody | 0; +var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; + +var headersComplete = 0; +var messagesComplete = 0; + +function flushPool() { + new Buffer(Buffer.poolSize - 1); + gc(); +} + +function demoBug(part1, part2) { + flushPool(); + + var parser = new HTTPParser('REQUEST'); + + parser.headers = []; + parser.url = ''; + + parser[kOnHeaders] = function(headers, url) { + parser.headers = parser.headers.concat(headers); + parser.url += url; + }; + + parser[kOnHeadersComplete] = function(info) { + headersComplete++; + console.log('url', info.url); + }; + + parser[kOnBody] = function(b, start, len) { }; + + parser[kOnMessageComplete] = function() { + messagesComplete++; + }; + + + // We use a function to eliminate references to the Buffer b + // We want b to be GCed. The parser will hold a bad reference to it. + (function() { + var b = Buffer(part1); + flushPool(); + + console.log('parse the first part of the message'); + parser.execute(b, 0, b.length); + })(); + + flushPool(); + + (function() { + var b = Buffer(part2); + + console.log('parse the second part of the message'); + parser.execute(b, 0, b.length); + parser.finish(); + })(); + + flushPool(); +} + + +demoBug('POST /1', '/22 HTTP/1.1\r\n' + + 'Content-Type: text/plain\r\n' + + 'Content-Length: 4\r\n\r\n' + + 'pong'); + +demoBug('POST /1/22 HTTP/1.1\r\n' + + 'Content-Type: tex', 't/plain\r\n' + + 'Content-Length: 4\r\n\r\n' + + 'pong'); + +process.on('exit', function() { + assert.equal(2, headersComplete); + assert.equal(2, messagesComplete); + console.log('done!'); +}); diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js new file mode 100644 index 000000000..7b35781f4 --- /dev/null +++ b/test/parallel/test-http-parser-free.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var N = 100; +var responses = 0; + +var server = http.createServer(function(req, res) { + res.end('Hello'); +}); + +server.listen(common.PORT, function() { + http.globalAgent.maxSockets = 1; + var parser; + for (var i = 0; i < N; ++i) { + (function makeRequest(i) { + var req = http.get({port: common.PORT}, function(res) { + if (!parser) { + parser = req.parser; + } else { + assert.strictEqual(req.parser, parser); + } + + if (++responses === N) { + server.close(); + } + res.resume(); + }); + })(i); + } +}); + +process.on('exit', function() { + assert.equal(responses, N); +}); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js new file mode 100644 index 000000000..c61dc9911 --- /dev/null +++ b/test/parallel/test-http-parser.js @@ -0,0 +1,570 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var HTTPParser = process.binding('http_parser').HTTPParser; + +var CRLF = '\r\n'; +var REQUEST = HTTPParser.REQUEST; +var RESPONSE = HTTPParser.RESPONSE; + +var methods = HTTPParser.methods; + +var kOnHeaders = HTTPParser.kOnHeaders | 0; +var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; +var kOnBody = HTTPParser.kOnBody | 0; +var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; + +// The purpose of this test is not to check HTTP compliance but to test the +// binding. Tests for pathological http messages should be submitted +// upstream to https://github.com/joyent/http-parser for inclusion into +// deps/http-parser/test.c + + +function newParser(type) { + var parser = new HTTPParser(type); + + parser.headers = []; + parser.url = ''; + + parser[kOnHeaders] = function(headers, url) { + parser.headers = parser.headers.concat(headers); + parser.url += url; + }; + + parser[kOnHeadersComplete] = function(info) { + }; + + parser[kOnBody] = function(b, start, len) { + assert.ok(false, 'Function should not be called.'); + }; + + parser[kOnMessageComplete] = function() { + }; + + return parser; +} + + +function mustCall(f, times) { + var actual = 0; + + process.setMaxListeners(256); + process.on('exit', function() { + assert.equal(actual, times || 1); + }); + + return function() { + actual++; + return f.apply(this, Array.prototype.slice.call(arguments)); + }; +} + + +function expectBody(expected) { + return mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, expected); + }); +} + + +// +// Simple request test. +// +(function() { + var request = Buffer( + 'GET /hello HTTP/1.1' + CRLF + + CRLF); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('GET')); + assert.equal(info.url || parser.url, '/hello'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + parser.execute(request, 0, request.length); + + // + // Check that if we throw an error in the callbacks that error will be + // thrown from parser.execute() + // + + parser[kOnHeadersComplete] = function(info) { + throw new Error('hello world'); + }; + + parser.reinitialize(HTTPParser.REQUEST); + + assert.throws(function() { + parser.execute(request, 0, request.length); + }, Error, 'hello world'); +})(); + + +// +// Simple response test. +// +(function() { + var request = Buffer( + 'HTTP/1.1 200 OK' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Content-Length: 4' + CRLF + + CRLF + + 'pong'); + + var parser = newParser(RESPONSE); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, undefined); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + assert.equal(info.statusCode, 200); + assert.equal(info.statusMessage, "OK"); + }); + + parser[kOnBody] = mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, 'pong'); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Response with no headers. +// +(function() { + var request = Buffer( + 'HTTP/1.0 200 Connection established' + CRLF + + CRLF); + + var parser = newParser(RESPONSE); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, undefined); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + assert.equal(info.statusCode, 200); + assert.equal(info.statusMessage, "Connection established"); + assert.deepEqual(info.headers || parser.headers, []); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Trailing headers. +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '4' + CRLF + + 'ping' + CRLF + + '0' + CRLF + + 'Vary: *' + CRLF + + 'Content-Type: text/plain' + CRLF + + CRLF); + + var seen_body = false; + + function onHeaders(headers, url) { + assert.ok(seen_body); // trailers should come after the body + assert.deepEqual(headers, + ['Vary', '*', 'Content-Type', 'text/plain']); + } + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + // expect to see trailing headers now + parser[kOnHeaders] = mustCall(onHeaders); + }); + + parser[kOnBody] = mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, 'ping'); + seen_body = true; + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test header ordering. +// +(function() { + var request = Buffer( + 'GET / HTTP/1.0' + CRLF + + 'X-Filler: 1337' + CRLF + + 'X-Filler: 42' + CRLF + + 'X-Filler2: 42' + CRLF + + CRLF); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('GET')); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + assert.deepEqual(info.headers || parser.headers, + ['X-Filler', '1337', + 'X-Filler', '42', + 'X-Filler2', '42']); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test large number of headers +// +(function() { + // 256 X-Filler headers + var lots_of_headers = 'X-Filler: 42' + CRLF; + for (var i = 0; i < 8; ++i) lots_of_headers += lots_of_headers; + + var request = Buffer( + 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + + lots_of_headers + + CRLF); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('GET')); + assert.equal(info.url || parser.url, '/foo/bar/baz?quux=42#1337'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + + var headers = info.headers || parser.headers; + + assert.equal(headers.length, 2 * 256); // 256 key/value pairs + for (var i = 0; i < headers.length; i += 2) { + assert.equal(headers[i], 'X-Filler'); + assert.equal(headers[i + 1], '42'); + } + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test request body +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: application/x-www-form-urlencoded' + CRLF + + 'Content-Length: 15' + CRLF + + CRLF + + 'foo=42&bar=1337'); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + parser[kOnBody] = mustCall(function(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, 'foo=42&bar=1337'); + }); + + parser.execute(request, 0, request.length); +})(); + + +// +// Test chunked request body +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF + + 'A' + CRLF + + '1234567890' + CRLF + + '0' + CRLF); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + var body_part = 0, + body_parts = ['123', '123456', '1234567890']; + + function onBody(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, body_parts[body_part++]); + } + + parser[kOnBody] = mustCall(onBody, body_parts.length); + parser.execute(request, 0, request.length); +})(); + + +// +// Test chunked request body spread over multiple buffers (packets) +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + var body_part = 0, + body_parts = [ + '123', '123456', '123456789', + '123456789ABC', '123456789ABCDEF']; + + function onBody(buf, start, len) { + var body = '' + buf.slice(start, start + len); + assert.equal(body, body_parts[body_part++]); + } + + parser[kOnBody] = mustCall(onBody, body_parts.length); + parser.execute(request, 0, request.length); + + request = Buffer( + '9' + CRLF + + '123456789' + CRLF + + 'C' + CRLF + + '123456789ABC' + CRLF + + 'F' + CRLF + + '123456789ABCDEF' + CRLF + + '0' + CRLF); + + parser.execute(request, 0, request.length); +})(); + + +// +// Stress test. +// +(function() { + var request = Buffer( + 'POST /helpme HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF + + '9' + CRLF + + '123456789' + CRLF + + 'C' + CRLF + + '123456789ABC' + CRLF + + 'F' + CRLF + + '123456789ABCDEF' + CRLF + + '0' + CRLF); + + function test(a, b) { + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url || parser.url, '/helpme'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + }); + + var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + + parser[kOnBody] = function(buf, start, len) { + var chunk = '' + buf.slice(start, start + len); + assert.equal(expected_body.indexOf(chunk), 0); + expected_body = expected_body.slice(chunk.length); + }; + + parser.execute(a, 0, a.length); + parser.execute(b, 0, b.length); + + assert.equal(expected_body, ''); + } + + for (var i = 1; i < request.length - 1; ++i) { + var a = request.slice(0, i); + console.error('request.slice(0, ' + i + ') = ', + JSON.stringify(a.toString())); + var b = request.slice(i); + console.error('request.slice(' + i + ') = ', + JSON.stringify(b.toString())); + test(a, b); + } +})(); + + +// +// Byte by byte test. +// +(function() { + var request = Buffer( + 'POST /it HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '3' + CRLF + + '123' + CRLF + + '6' + CRLF + + '123456' + CRLF + + '9' + CRLF + + '123456789' + CRLF + + 'C' + CRLF + + '123456789ABC' + CRLF + + 'F' + CRLF + + '123456789ABCDEF' + CRLF + + '0' + CRLF); + + var parser = newParser(REQUEST); + + parser[kOnHeadersComplete] = mustCall(function(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url || parser.url, '/it'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + assert.deepEqual(info.headers || parser.headers, + ['Content-Type', 'text/plain', + 'Transfer-Encoding', 'chunked']); + }); + + var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + + parser[kOnBody] = function(buf, start, len) { + var chunk = '' + buf.slice(start, start + len); + assert.equal(expected_body.indexOf(chunk), 0); + expected_body = expected_body.slice(chunk.length); + }; + + for (var i = 0; i < request.length; ++i) { + parser.execute(request, i, 1); + } + + assert.equal(expected_body, ''); +})(); + + +// +// Test parser reinit sequence. +// +(function() { + var req1 = Buffer( + 'PUT /this HTTP/1.1' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Transfer-Encoding: chunked' + CRLF + + CRLF + + '4' + CRLF + + 'ping' + CRLF + + '0' + CRLF); + + var req2 = Buffer( + 'POST /that HTTP/1.0' + CRLF + + 'Content-Type: text/plain' + CRLF + + 'Content-Length: 4' + CRLF + + CRLF + + 'pong'); + + function onHeadersComplete1(info) { + assert.equal(info.method, methods.indexOf('PUT')); + assert.equal(info.url, '/this'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 1); + assert.deepEqual(info.headers, + ['Content-Type', 'text/plain', + 'Transfer-Encoding', 'chunked']); + }; + + function onHeadersComplete2(info) { + assert.equal(info.method, methods.indexOf('POST')); + assert.equal(info.url, '/that'); + assert.equal(info.versionMajor, 1); + assert.equal(info.versionMinor, 0); + assert.deepEqual(info.headers, + ['Content-Type', 'text/plain', + 'Content-Length', '4']); + }; + + var parser = newParser(REQUEST); + parser[kOnHeadersComplete] = onHeadersComplete1; + parser[kOnBody] = expectBody('ping'); + parser.execute(req1, 0, req1.length); + + parser.reinitialize(REQUEST); + parser[kOnBody] = expectBody('pong'); + parser[kOnHeadersComplete] = onHeadersComplete2; + parser.execute(req2, 0, req2.length); +})(); + +// Test parser 'this' safety +// https://github.com/joyent/node/issues/6690 +assert.throws(function() { + var request = Buffer( + 'GET /hello HTTP/1.1' + CRLF + + CRLF); + + var parser = newParser(REQUEST); + var notparser = { execute: parser.execute }; + notparser.execute(request, 0, request.length); +}, TypeError); diff --git a/test/parallel/test-http-pause-resume-one-end.js b/test/parallel/test-http-pause-resume-one-end.js new file mode 100644 index 000000000..f397452e9 --- /dev/null +++ b/test/parallel/test-http-pause-resume-one-end.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.Server(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('Hello World\n'); + server.close(); +}); + + +var dataCount = 0, endCount = 0; + +server.listen(common.PORT, function() { + var opts = { + port: common.PORT, + headers: { connection: 'close' } + }; + + http.get(opts, function(res) { + res.on('data', function(chunk) { + dataCount++; + res.pause(); + setTimeout(function() { + res.resume(); + }); + }); + + res.on('end', function() { + endCount++; + }); + }); +}); + + +process.on('exit', function() { + assert.equal(1, dataCount); + assert.equal(1, endCount); +}); diff --git a/test/parallel/test-http-pause.js b/test/parallel/test-http-pause.js new file mode 100644 index 000000000..0edf6d622 --- /dev/null +++ b/test/parallel/test-http-pause.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expectedServer = 'Request Body from Client'; +var resultServer = ''; +var expectedClient = 'Response Body from Server'; +var resultClient = ''; + +var server = http.createServer(function(req, res) { + common.debug('pause server request'); + req.pause(); + setTimeout(function() { + common.debug('resume server request'); + req.resume(); + req.setEncoding('utf8'); + req.on('data', function(chunk) { + resultServer += chunk; + }); + req.on('end', function() { + common.debug(resultServer); + res.writeHead(200); + res.end(expectedClient); + }); + }, 100); +}); + +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }, function(res) { + common.debug('pause client response'); + res.pause(); + setTimeout(function() { + common.debug('resume client response'); + res.resume(); + res.on('data', function(chunk) { + resultClient += chunk; + }); + res.on('end', function() { + common.debug(resultClient); + server.close(); + }); + }, 100); + }); + req.end(expectedServer); +}); + +process.on('exit', function() { + assert.equal(expectedServer, resultServer); + assert.equal(expectedClient, resultClient); +}); diff --git a/test/parallel/test-http-pipe-fs.js b/test/parallel/test-http-pipe-fs.js new file mode 100644 index 000000000..57ebb11dc --- /dev/null +++ b/test/parallel/test-http-pipe-fs.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var fs = require('fs'); +var path = require('path'); + +var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); +var requests = 0; + +var server = http.createServer(function(req, res) { + ++requests; + var stream = fs.createWriteStream(file); + req.pipe(stream); + stream.on('close', function() { + res.writeHead(200); + res.end(); + }); +}).listen(common.PORT, function() { + http.globalAgent.maxSockets = 1; + + for (var i = 0; i < 2; ++i) { + (function(i) { + var req = http.request({ + port: common.PORT, + method: 'POST', + headers: { + 'Content-Length': 5 + } + }, function(res) { + res.on('end', function() { + common.debug('res' + i + ' end'); + if (i === 2) { + server.close(); + } + }); + res.resume(); + }); + req.on('socket', function(s) { + common.debug('req' + i + ' start'); + }); + req.end('12345'); + }(i + 1)); + } +}); + +process.on('exit', function() { + assert.equal(requests, 2); +}); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js new file mode 100644 index 000000000..b531f1a8a --- /dev/null +++ b/test/parallel/test-http-proxy.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var PROXY_PORT = common.PORT; +var BACKEND_PORT = common.PORT + 1; + +var cookies = [ + 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', + 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' +]; + +var headers = {'content-type': 'text/plain', + 'set-cookie': cookies, + 'hello': 'world' }; + +var backend = http.createServer(function(req, res) { + console.error('backend request'); + res.writeHead(200, headers); + res.write('hello world\n'); + res.end(); +}); + +var proxy = http.createServer(function(req, res) { + console.error('proxy req headers: ' + JSON.stringify(req.headers)); + var proxy_req = http.get({ + port: BACKEND_PORT, + path: url.parse(req.url).pathname + }, function(proxy_res) { + + console.error('proxy res headers: ' + JSON.stringify(proxy_res.headers)); + + assert.equal('world', proxy_res.headers['hello']); + assert.equal('text/plain', proxy_res.headers['content-type']); + assert.deepEqual(cookies, proxy_res.headers['set-cookie']); + + res.writeHead(proxy_res.statusCode, proxy_res.headers); + + proxy_res.on('data', function(chunk) { + res.write(chunk); + }); + + proxy_res.on('end', function() { + res.end(); + console.error('proxy res'); + }); + }); +}); + +var body = ''; + +var nlistening = 0; +function startReq() { + nlistening++; + if (nlistening < 2) return; + + var client = http.get({ + port: PROXY_PORT, + path: '/test' + }, function(res) { + console.error('got res'); + assert.equal(200, res.statusCode); + + assert.equal('world', res.headers['hello']); + assert.equal('text/plain', res.headers['content-type']); + assert.deepEqual(cookies, res.headers['set-cookie']); + + res.setEncoding('utf8'); + res.on('data', function(chunk) { body += chunk; }); + res.on('end', function() { + proxy.close(); + backend.close(); + console.error('closed both'); + }); + }); + console.error('client req'); +} + +console.error('listen proxy'); +proxy.listen(PROXY_PORT, startReq); + +console.error('listen backend'); +backend.listen(BACKEND_PORT, startReq); + +process.on('exit', function() { + assert.equal(body, 'hello world\n'); +}); diff --git a/test/parallel/test-http-raw-headers.js b/test/parallel/test-http-raw-headers.js new file mode 100644 index 000000000..0d31d8f61 --- /dev/null +++ b/test/parallel/test-http-raw-headers.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +http.createServer(function(req, res) { + this.close(); + var expectRawHeaders = [ + 'Host', + 'localhost:' + common.PORT, + 'transfer-ENCODING', + 'CHUNKED', + 'x-BaR', + 'yoyoyo', + 'Connection', + 'close' + ]; + var expectHeaders = { + host: 'localhost:' + common.PORT, + 'transfer-encoding': 'CHUNKED', + 'x-bar': 'yoyoyo', + connection: 'close' + }; + + var expectRawTrailers = [ + 'x-bAr', + 'yOyOyOy', + 'x-baR', + 'OyOyOyO', + 'X-bAr', + 'yOyOyOy', + 'X-baR', + 'OyOyOyO' + ]; + + var expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; + + assert.deepEqual(req.rawHeaders, expectRawHeaders); + assert.deepEqual(req.headers, expectHeaders); + + req.on('end', function() { + assert.deepEqual(req.rawTrailers, expectRawTrailers); + assert.deepEqual(req.trailers, expectTrailers); + }); + + req.resume(); + res.addTrailers([ + ['x-fOo', 'xOxOxOx'], + ['x-foO', 'OxOxOxO'], + ['X-fOo', 'xOxOxOx'], + ['X-foO', 'OxOxOxO'] + ]); + res.end('x f o o'); +}).listen(common.PORT, function() { + var expectRawHeaders = [ + 'Date', + 'Tue, 06 Aug 2013 01:31:54 GMT', + 'Connection', + 'close', + 'Transfer-Encoding', + 'chunked' + ]; + var req = http.request({ port: common.PORT, path: '/' }); + req.addTrailers([ + ['x-bAr', 'yOyOyOy'], + ['x-baR', 'OyOyOyO'], + ['X-bAr', 'yOyOyOy'], + ['X-baR', 'OyOyOyO'] + ]); + req.setHeader('transfer-ENCODING', 'CHUNKED'); + req.setHeader('x-BaR', 'yoyoyo'); + req.end('y b a r'); + req.on('response', function(res) { + var expectRawHeaders = [ + 'Date', + null, + 'Connection', + 'close', + 'Transfer-Encoding', + 'chunked' + ]; + var expectHeaders = { + date: null, + connection: 'close', + 'transfer-encoding': 'chunked' + }; + res.rawHeaders[1] = null; + res.headers.date = null; + assert.deepEqual(res.rawHeaders, expectRawHeaders); + assert.deepEqual(res.headers, expectHeaders); + res.on('end', function() { + var expectRawTrailers = [ + 'x-fOo', + 'xOxOxOx', + 'x-foO', + 'OxOxOxO', + 'X-fOo', + 'xOxOxOx', + 'X-foO', + 'OxOxOxO' + ]; + var expectTrailers = { 'x-foo': 'xOxOxOx, OxOxOxO, xOxOxOx, OxOxOxO' }; + + assert.deepEqual(res.rawTrailers, expectRawTrailers); + assert.deepEqual(res.trailers, expectTrailers); + console.log('ok'); + }); + res.resume(); + }); +}); diff --git a/test/parallel/test-http-remove-header-stays-removed.js b/test/parallel/test-http-remove-header-stays-removed.js new file mode 100644 index 000000000..a15c7750c --- /dev/null +++ b/test/parallel/test-http-remove-header-stays-removed.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var server = http.createServer(function(request, response) { + // removed headers should stay removed, even if node automatically adds them + // to the output: + response.removeHeader('connection'); + response.removeHeader('transfer-encoding'); + + // make sure that removing and then setting still works: + response.removeHeader('date'); + response.setHeader('date', 'coffee o clock'); + + response.end('beep boop\n'); + + this.close(); +}); + +var response = ''; + +process.on('exit', function() { + assert.equal('beep boop\n', response); + console.log('ok'); +}); + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + assert.equal(200, res.statusCode); + assert.deepEqual(res.headers, { date : 'coffee o clock' }); + + res.setEncoding('ascii'); + res.on('data', function(chunk) { + response += chunk; + }); + }); +}); diff --git a/test/parallel/test-http-request-end-twice.js b/test/parallel/test-http-request-end-twice.js new file mode 100644 index 000000000..aa5877222 --- /dev/null +++ b/test/parallel/test-http-request-end-twice.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.Server(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('hello world\n'); +}); +server.listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + res.on('end', function() { + assert.ok(!req.end()); + server.close(); + }); + res.resume(); + }); +}); + diff --git a/test/parallel/test-http-request-end.js b/test/parallel/test-http-request-end.js new file mode 100644 index 000000000..f64dcc305 --- /dev/null +++ b/test/parallel/test-http-request-end.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var expected = 'Post Body For Test'; +var result = ''; + +var server = http.Server(function(req, res) { + req.setEncoding('utf8'); + req.on('data', function(chunk) { + result += chunk; + }); + + req.on('end', function() { + server.close(); + }); + + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(common.PORT, function() { + http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }, function(res) { + console.log(res.statusCode); + res.resume(); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }).end(expected); +}); + +process.on('exit', function() { + assert.equal(expected, result); +}); diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js new file mode 100644 index 000000000..33575aed7 --- /dev/null +++ b/test/parallel/test-http-request-methods.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +// Test that the DELETE, PATCH and PURGE verbs get passed through correctly + +['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { + var port = common.PORT + index; + + var server_response = ''; + var received_method = null; + + var server = http.createServer(function(req, res) { + received_method = req.method; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello '); + res.write('world\n'); + res.end(); + }); + server.listen(port); + + server.on('listening', function() { + var c = net.createConnection(port); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write(method + ' / HTTP/1.0\r\n\r\n'); + }); + + c.on('data', function(chunk) { + console.log(chunk); + server_response += chunk; + }); + + c.on('end', function() { + c.end(); + }); + + c.on('close', function() { + server.close(); + }); + }); + + process.on('exit', function() { + var m = server_response.split('\r\n\r\n'); + assert.equal(m[1], 'hello world\n'); + assert.equal(received_method, method); + }); +}); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js new file mode 100644 index 000000000..71a2564bf --- /dev/null +++ b/test/parallel/test-http-res-write-after-end.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var responseError; + +var server = http.Server(function(req, res) { + res.on('error', function onResError(err) { + responseError = err; + }); + + res.write('This should write.'); + res.end(); + + var r = res.write('This should raise an error.'); + assert.equal(r, true, 'write after end should return true'); +}); + +server.listen(common.PORT, function() { + var req = http.get({port: common.PORT}, function(res) { + server.close(); + }); +}); + +process.on('exit', function onProcessExit(code) { + assert(responseError, 'response should have emitted error'); + assert.equal(responseError.message, 'write after end'); +}); diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js new file mode 100644 index 000000000..d60b75552 --- /dev/null +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var test = 1; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + if (test === 1) { + // write should accept string + res.write('string'); + // write should accept buffer + res.write(new Buffer('asdf')); + + // write should not accept an Array + assert.throws(function() { + res.write(['array']); + }, TypeError, 'first argument must be a string or Buffer'); + + // end should not accept an Array + assert.throws(function() { + res.end(['moo']); + }, TypeError, 'first argument must be a string or Buffer'); + + // end should accept string + res.end('string'); + } else if (test === 2) { + // end should accept Buffer + res.end(new Buffer('asdf')); + } +}); + +server.listen(common.PORT, function() { + // just make a request, other tests handle responses + http.get({port: common.PORT}, function(res) { + res.resume(); + // lazy serial test, because we can only call end once per request + test += 1; + // do it again to test .end(Buffer); + http.get({port: common.PORT}, function(res) { + res.resume(); + server.close(); + }); + }); +}); diff --git a/test/parallel/test-http-response-close.js b/test/parallel/test-http-response-close.js new file mode 100644 index 000000000..be89682a6 --- /dev/null +++ b/test/parallel/test-http-response-close.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var requestGotEnd = false; +var responseGotEnd = false; + +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.write('a'); + + req.on('close', function() { + console.error('request aborted'); + requestGotEnd = true; + }); + res.on('close', function() { + console.error('response aborted'); + responseGotEnd = true; + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + console.error('make req'); + http.get({ + port: common.PORT + }, function(res) { + console.error('got res'); + res.on('data', function(data) { + console.error('destroy res'); + res.destroy(); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.ok(requestGotEnd); + assert.ok(responseGotEnd); +}); diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js new file mode 100644 index 000000000..d16d8a4ce --- /dev/null +++ b/test/parallel/test-http-response-no-headers.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var expected = { + '0.9': 'I AM THE WALRUS', + '1.0': 'I AM THE WALRUS', + '1.1': '' +}; + +var gotExpected = false; + +function test(httpVersion, callback) { + process.on('exit', function() { + assert(gotExpected); + }); + + var server = net.createServer(function(conn) { + var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + + expected[httpVersion]; + + conn.end(reply); + }); + + server.listen(common.PORT, '127.0.0.1', function() { + var options = { + host: '127.0.0.1', + port: common.PORT + }; + + var req = http.get(options, function(res) { + var body = ''; + + res.on('data', function(data) { + body += data; + }); + + res.on('end', function() { + assert.equal(body, expected[httpVersion]); + gotExpected = true; + server.close(); + if (callback) process.nextTick(callback); + }); + }); + + req.on('error', function(err) { + throw err; + }); + }); +} + +test('0.9', function() { + test('1.0', function() { + test('1.1'); + }); +}); diff --git a/test/parallel/test-http-response-readable.js b/test/parallel/test-http-response-readable.js new file mode 100644 index 000000000..b48c06fb4 --- /dev/null +++ b/test/parallel/test-http-response-readable.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var testServer = new http.Server(function(req, res) { + res.writeHead(200); + res.end('Hello world'); +}); + +testServer.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + assert.equal(res.readable, true, 'res.readable initially true'); + res.on('end', function() { + assert.equal(res.readable, false, 'res.readable set to false after end'); + testServer.close(); + }); + res.resume(); + }); +}); + diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js new file mode 100644 index 000000000..3b3911010 --- /dev/null +++ b/test/parallel/test-http-response-status-message.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var testsComplete = 0; + +var testCases = [ + { path: "/200", statusMessage: "OK", response: 'HTTP/1.1 200 OK\r\n\r\n' }, + { path: "/500", statusMessage: "Internal Server Error", response: 'HTTP/1.1 500 Internal Server Error\r\n\r\n' }, + { path: "/302", statusMessage: "Moved Temporarily", response: 'HTTP/1.1 302 Moved Temporarily\r\n\r\n' }, + { path: "/missing", statusMessage: "", response: 'HTTP/1.1 200 \r\n\r\n' }, + { path: "/missing-no-space", statusMessage: "", response: 'HTTP/1.1 200\r\n\r\n' } +]; +testCases.findByPath = function(path) { + var matching = this.filter(function(testCase) { return testCase.path === path; }); + if (matching.length === 0) { throw "failed to find test case with path " + path; } + return matching[0]; +}; + +var server = net.createServer(function(connection) { + connection.on('data', function(data) { + var path = data.toString().match(/GET (.*) HTTP.1.1/)[1]; + var testCase = testCases.findByPath(path); + + connection.write(testCase.response); + connection.end(); + }); +}); + +var runTest = function(testCaseIndex) { + var testCase = testCases[testCaseIndex]; + + http.get({ port: common.PORT, path: testCase.path }, function(response) { + console.log('client: expected status message: ' + testCase.statusMessage); + console.log('client: actual status message: ' + response.statusMessage); + assert.equal(testCase.statusMessage, response.statusMessage); + + response.on('end', function() { + testsComplete++; + + if (testCaseIndex + 1 < testCases.length) { + runTest(testCaseIndex + 1); + } else { + server.close(); + } + }); + + response.resume(); + }); +}; + +server.listen(common.PORT, function() { runTest(0); }); + +process.on('exit', function() { + assert.equal(testCases.length, testsComplete); +}); diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js new file mode 100644 index 000000000..b287169bd --- /dev/null +++ b/test/parallel/test-http-server-multiheaders.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the HTTP server implementation handles multiple instances +// of the same header as per RFC2616: joining the handful of fields by ', ' +// that support it, and dropping duplicates for other fields. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var srv = http.createServer(function(req, res) { + assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); + assert.equal(req.headers.host, 'foo'); + assert.equal(req.headers['www-authenticate'], 'foo, bar, baz'); + assert.equal(req.headers['proxy-authenticate'], 'foo, bar, baz'); + assert.equal(req.headers['x-foo'], 'bingo'); + assert.equal(req.headers['x-bar'], 'banjo, bango'); + assert.equal(req.headers['sec-websocket-protocol'], 'chat, share'); + assert.equal(req.headers['sec-websocket-extensions'], 'foo; 1, bar; 2, baz'); + + res.writeHead(200, {'Content-Type' : 'text/plain'}); + res.end('EOF'); + + srv.close(); +}); + +srv.listen(common.PORT, function() { + http.get({ + host: 'localhost', + port: common.PORT, + path: '/', + headers: [ + ['accept', 'abc'], + ['accept', 'def'], + ['Accept', 'ghijklmnopqrst'], + ['host', 'foo'], + ['Host', 'bar'], + ['hOst', 'baz'], + ['www-authenticate', 'foo'], + ['WWW-Authenticate', 'bar'], + ['WWW-AUTHENTICATE', 'baz'], + ['proxy-authenticate','foo'], + ['Proxy-Authenticate','bar'], + ['PROXY-AUTHENTICATE','baz'], + ['x-foo', 'bingo'], + ['x-bar', 'banjo'], + ['x-bar', 'bango'], + ['sec-websocket-protocol', 'chat'], + ['sec-websocket-protocol', 'share'], + ['sec-websocket-extensions', 'foo; 1'], + ['sec-websocket-extensions', 'bar; 2'], + ['sec-websocket-extensions', 'baz'] + ] + }); +}); diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js new file mode 100644 index 000000000..40674c0fc --- /dev/null +++ b/test/parallel/test-http-server-multiheaders2.js @@ -0,0 +1,108 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the HTTP server implementation handles multiple instances +// of the same header as per RFC2616: joining the handful of fields by ', ' +// that support it, and dropping duplicates for other fields. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var multipleAllowed = [ + 'Accept', + 'Accept-Charset', + 'Accept-Encoding', + 'Accept-Language', + 'Connection', + 'Cookie', + 'DAV', // GH-2750 + 'Pragma', // GH-715 + 'Link', // GH-1187 + 'WWW-Authenticate', // GH-1083 + 'Proxy-Authenticate', // GH-4052 + 'Sec-Websocket-Extensions', // GH-2764 + 'Sec-Websocket-Protocol', // GH-2764 + 'Via', // GH-6660 + + // not a special case, just making sure it's parsed correctly + 'X-Forwarded-For', + + // make sure that unspecified headers is treated as multiple + 'Some-Random-Header', + 'X-Some-Random-Header', +]; + +var multipleForbidden = [ + 'Content-Type', + 'User-Agent', + 'Referer', + 'Host', + 'Authorization', + 'Proxy-Authorization', + 'If-Modified-Since', + 'If-Unmodified-Since', + 'From', + 'Location', + 'Max-Forwards', + + // special case, tested differently + //'Content-Length', +]; + +var srv = http.createServer(function(req, res) { + multipleForbidden.forEach(function(header) { + assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header); + }); + multipleAllowed.forEach(function(header) { + assert.equal(req.headers[header.toLowerCase()], 'foo, bar', 'header parsed incorrectly: ' + header); + }); + assert.equal(req.headers['content-length'], 0); + + res.writeHead(200, {'Content-Type' : 'text/plain'}); + res.end('EOF'); + + srv.close(); +}); + +function makeHeader(value) { + return function(header) { + return [header, value]; + } +} + +var headers = [] + .concat(multipleAllowed.map(makeHeader('foo'))) + .concat(multipleForbidden.map(makeHeader('foo'))) + .concat(multipleAllowed.map(makeHeader('bar'))) + .concat(multipleForbidden.map(makeHeader('bar'))) + // content-length is a special case since node.js + // is dropping connetions with non-numeric headers + .concat([['content-length', 0], ['content-length', 123]]); + +srv.listen(common.PORT, function() { + http.get({ + host: 'localhost', + port: common.PORT, + path: '/', + headers: headers, + }); +}); diff --git a/test/parallel/test-http-server-stale-close.js b/test/parallel/test-http-server-stale-close.js new file mode 100644 index 000000000..aa42a049b --- /dev/null +++ b/test/parallel/test-http-server-stale-close.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var util = require('util'); +var fork = require('child_process').fork; + +if (process.env.NODE_TEST_FORK) { + var req = http.request({ + headers: {'Content-Length': '42'}, + method: 'POST', + host: '127.0.0.1', + port: common.PORT, + }, process.exit); + req.write('BAM'); + req.end(); +} +else { + var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Length': '42'}); + req.pipe(res); + req.on('close', function() { + server.close(); + res.end(); + }); + }); + server.listen(common.PORT, function() { + fork(__filename, { + env: util._extend(process.env, {NODE_TEST_FORK: '1'}) + }); + }); +} diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js new file mode 100644 index 000000000..7d97382d3 --- /dev/null +++ b/test/parallel/test-http-server.js @@ -0,0 +1,128 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); +var url = require('url'); +var qs = require('querystring'); + +var request_number = 0; +var requests_sent = 0; +var server_response = ''; +var client_got_eof = false; + +var server = http.createServer(function(req, res) { + res.id = request_number; + req.id = request_number++; + + if (req.id == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + assert.equal('world', qs.parse(url.parse(req.url).query).hello); + assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo); + } + + if (req.id == 1) { + common.error('req 1'); + assert.equal('POST', req.method); + assert.equal('/quit', url.parse(req.url).pathname); + } + + if (req.id == 2) { + common.error('req 2'); + assert.equal('foo', req.headers['x-x']); + } + + if (req.id == 3) { + common.error('req 3'); + assert.equal('bar', req.headers['x-x']); + this.close(); + common.error('server closed'); + } + + setTimeout(function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write(url.parse(req.url).pathname); + res.end(); + }, 1); + +}); +server.listen(common.PORT); + +server.httpAllowHalfOpen = true; + +server.on('listening', function() { + var c = net.createConnection(common.PORT); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n'); + requests_sent += 1; + }); + + c.on('data', function(chunk) { + server_response += chunk; + + if (requests_sent == 1) { + c.write('POST /quit HTTP/1.1\r\n\r\n'); + requests_sent += 1; + } + + if (requests_sent == 2) { + c.write('GET / HTTP/1.1\r\nX-X: foo\r\n\r\n' + + 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n'); + // Note: we are making the connection half-closed here + // before we've gotten the response from the server. This + // is a pretty bad thing to do and not really supported + // by many http servers. Node supports it optionally if + // you set server.httpAllowHalfOpen=true, which we've done + // above. + c.end(); + assert.equal(c.readyState, 'readOnly'); + requests_sent += 2; + } + + }); + + c.on('end', function() { + client_got_eof = true; + }); + + c.on('close', function() { + assert.equal(c.readyState, 'closed'); + }); +}); + +process.on('exit', function() { + assert.equal(4, request_number); + assert.equal(4, requests_sent); + + var hello = new RegExp('/hello'); + assert.equal(true, hello.exec(server_response) != null); + + var quit = new RegExp('/quit'); + assert.equal(true, quit.exec(server_response) != null); + + assert.equal(true, client_got_eof); +}); diff --git a/test/parallel/test-http-set-cookies.js b/test/parallel/test-http-set-cookies.js new file mode 100644 index 000000000..bff34d829 --- /dev/null +++ b/test/parallel/test-http-set-cookies.js @@ -0,0 +1,84 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var nresponses = 0; + +var server = http.createServer(function(req, res) { + if (req.url == '/one') { + res.writeHead(200, [['set-cookie', 'A'], + ['content-type', 'text/plain']]); + res.end('one\n'); + } else { + res.writeHead(200, [['set-cookie', 'A'], + ['set-cookie', 'B'], + ['content-type', 'text/plain']]); + res.end('two\n'); + } +}); +server.listen(common.PORT); + +server.on('listening', function() { + // + // one set-cookie header + // + http.get({ port: common.PORT, path: '/one' }, function(res) { + // set-cookie headers are always return in an array. + // even if there is only one. + assert.deepEqual(['A'], res.headers['set-cookie']); + assert.equal('text/plain', res.headers['content-type']); + + res.on('data', function(chunk) { + console.log(chunk.toString()); + }); + + res.on('end', function() { + if (++nresponses == 2) { + server.close(); + } + }); + }); + + // two set-cookie headers + + http.get({ port: common.PORT, path: '/two' }, function(res) { + assert.deepEqual(['A', 'B'], res.headers['set-cookie']); + assert.equal('text/plain', res.headers['content-type']); + + res.on('data', function(chunk) { + console.log(chunk.toString()); + }); + + res.on('end', function() { + if (++nresponses == 2) { + server.close(); + } + }); + }); + +}); + +process.on('exit', function() { + assert.equal(2, nresponses); +}); diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js new file mode 100644 index 000000000..ff4144963 --- /dev/null +++ b/test/parallel/test-http-set-timeout-server.js @@ -0,0 +1,179 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var tests = []; + +function test(fn) { + if (!tests.length) + process.nextTick(run); + tests.push(fn); +} + +function run() { + var fn = tests.shift(); + if (fn) { + console.log('# %s', fn.name); + fn(run); + } else + console.log('ok'); +} + +test(function serverTimeout(cb) { + var caughtTimeout = false; + process.on('exit', function() { + assert(caughtTimeout); + }); + var server = http.createServer(function(req, res) { + // just do nothing, we should get a timeout event. + }); + server.listen(common.PORT); + server.setTimeout(50, function(socket) { + caughtTimeout = true; + socket.destroy(); + server.close(); + cb(); + }); + http.get({ port: common.PORT }).on('error', function() {}); +}); + +test(function serverRequestTimeout(cb) { + var caughtTimeout = false; + process.on('exit', function() { + assert(caughtTimeout); + }); + var server = http.createServer(function(req, res) { + // just do nothing, we should get a timeout event. + req.setTimeout(50, function() { + caughtTimeout = true; + req.socket.destroy(); + server.close(); + cb(); + }); + }); + server.listen(common.PORT); + var req = http.request({ port: common.PORT, method: 'POST' }); + req.on('error', function() {}); + req.write('Hello'); + // req is in progress +}); + +test(function serverResponseTimeout(cb) { + var caughtTimeout = false; + process.on('exit', function() { + assert(caughtTimeout); + }); + var server = http.createServer(function(req, res) { + // just do nothing, we should get a timeout event. + res.setTimeout(50, function() { + caughtTimeout = true; + res.socket.destroy(); + server.close(); + cb(); + }); + }); + server.listen(common.PORT); + http.get({ port: common.PORT }).on('error', function() {}); +}); + +test(function serverRequestNotTimeoutAfterEnd(cb) { + var caughtTimeoutOnRequest = false; + var caughtTimeoutOnResponse = false; + process.on('exit', function() { + assert(!caughtTimeoutOnRequest); + assert(caughtTimeoutOnResponse); + }); + var server = http.createServer(function(req, res) { + // just do nothing, we should get a timeout event. + req.setTimeout(50, function(socket) { + caughtTimeoutOnRequest = true; + }); + res.on('timeout', function(socket) { + caughtTimeoutOnResponse = true; + }); + }); + server.on('timeout', function(socket) { + socket.destroy(); + server.close(); + cb(); + }); + server.listen(common.PORT); + http.get({ port: common.PORT }).on('error', function() {}); +}); + +test(function serverResponseTimeoutWithPipeline(cb) { + var caughtTimeout = ''; + process.on('exit', function() { + assert.equal(caughtTimeout, '/2'); + }); + var server = http.createServer(function(req, res) { + res.setTimeout(50, function() { + caughtTimeout += req.url; + }); + if (req.url === '/1') res.end(); + }); + server.on('timeout', function(socket) { + socket.destroy(); + server.close(); + cb(); + }); + server.listen(common.PORT); + var c = net.connect({ port: common.PORT, allowHalfOpen: true }, function() { + c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + }); +}); + +test(function idleTimeout(cb) { + var caughtTimeoutOnRequest = false; + var caughtTimeoutOnResponse = false; + var caughtTimeoutOnServer = false; + process.on('exit', function() { + assert(!caughtTimeoutOnRequest); + assert(!caughtTimeoutOnResponse); + assert(caughtTimeoutOnServer); + }); + var server = http.createServer(function(req, res) { + req.on('timeout', function(socket) { + caughtTimeoutOnRequest = true; + }); + res.on('timeout', function(socket) { + caughtTimeoutOnResponse = true; + }); + res.end(); + }); + server.setTimeout(50, function(socket) { + caughtTimeoutOnServer = true; + socket.destroy(); + server.close(); + cb(); + }); + server.listen(common.PORT); + var c = net.connect({ port: common.PORT, allowHalfOpen: true }, function() { + c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + // Keep-Alive + }); +}); diff --git a/test/parallel/test-http-set-timeout.js b/test/parallel/test-http-set-timeout.js new file mode 100644 index 000000000..01d182b34 --- /dev/null +++ b/test/parallel/test-http-set-timeout.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + console.log('got request. setting 1 second timeout'); + req.connection.setTimeout(500); + + req.connection.on('timeout', function() { + req.connection.destroy(); + common.debug('TIMEOUT'); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); + + var errorTimer = setTimeout(function() { + throw new Error('Timeout was not successful'); + }, 2000); + + var x = http.get({port: common.PORT, path: '/'}); + x.on('error', function() { + clearTimeout(errorTimer); + console.log('HTTP REQUEST COMPLETE (this is good)'); + }); + x.end(); + +}); diff --git a/test/parallel/test-http-set-trailers.js b/test/parallel/test-http-set-trailers.js new file mode 100644 index 000000000..445a3eeaa --- /dev/null +++ b/test/parallel/test-http-set-trailers.js @@ -0,0 +1,112 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var outstanding_reqs = 0; + +var server = http.createServer(function(req, res) { + res.writeHead(200, [['content-type', 'text/plain']]); + res.addTrailers({'x-foo': 'bar'}); + res.end('stuff' + '\n'); +}); +server.listen(common.PORT); + + +// first, we test an HTTP/1.0 request. +server.on('listening', function() { + var c = net.createConnection(common.PORT); + var res_buffer = ''; + + c.setEncoding('utf8'); + + c.on('connect', function() { + outstanding_reqs++; + c.write('GET / HTTP/1.0\r\n\r\n'); + }); + + c.on('data', function(chunk) { + //console.log(chunk); + res_buffer += chunk; + }); + + c.on('end', function() { + c.end(); + assert.ok(! /x-foo/.test(res_buffer), 'Trailer in HTTP/1.0 response.'); + outstanding_reqs--; + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + }); +}); + +// now, we test an HTTP/1.1 request. +server.on('listening', function() { + var c = net.createConnection(common.PORT); + var res_buffer = ''; + var tid; + + c.setEncoding('utf8'); + + c.on('connect', function() { + outstanding_reqs++; + c.write('GET / HTTP/1.1\r\n\r\n'); + tid = setTimeout(assert.fail, 2000, 'Couldn\'t find last chunk.'); + }); + + c.on('data', function(chunk) { + //console.log(chunk); + res_buffer += chunk; + if (/0\r\n/.test(res_buffer)) { // got the end. + outstanding_reqs--; + clearTimeout(tid); + assert.ok( + /0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer), + 'No trailer in HTTP/1.1 response.' + ); + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + } + }); +}); + +// now, see if the client sees the trailers. +server.on('listening', function() { + http.get({ port: common.PORT, path: '/hello', headers: {} }, function(res) { + res.on('end', function() { + //console.log(res.trailers); + assert.ok('x-foo' in res.trailers, 'Client doesn\'t see trailers.'); + outstanding_reqs--; + if (outstanding_reqs == 0) { + server.close(); + process.exit(); + } + }); + res.resume(); + }); + outstanding_reqs++; +}); diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js new file mode 100644 index 000000000..943c34bb4 --- /dev/null +++ b/test/parallel/test-http-should-keep-alive.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var SERVER_RESPONSES = [ + 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n', + 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', + 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n', + 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n', + 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', + 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' +]; +var SHOULD_KEEP_ALIVE = [ + false, // HTTP/1.0, default + true, // HTTP/1.0, Connection: keep-alive + false, // HTTP/1.0, Connection: close + true, // HTTP/1.1, default + true, // HTTP/1.1, Connection: keep-alive + false // HTTP/1.1, Connection: close +]; +var requests = 0; +var responses = 0; +http.globalAgent.maxSockets = 5; + +var server = net.createServer(function(socket) { + socket.write(SERVER_RESPONSES[requests]); + ++requests; +}).listen(common.PORT, function() { + function makeRequest() { + var req = http.get({port: common.PORT}, function(res) { + assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], + SERVER_RESPONSES[responses] + ' should ' + + (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + + 'Keep-Alive'); + ++responses; + if (responses < SHOULD_KEEP_ALIVE.length) { + makeRequest(); + } else { + server.close(); + } + res.resume(); + }); + } + + makeRequest(); +}); + +process.on('exit', function() { + assert.equal(requests, SERVER_RESPONSES.length); + assert.equal(responses, SHOULD_KEEP_ALIVE.length); +}); diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js new file mode 100644 index 000000000..ca56230d2 --- /dev/null +++ b/test/parallel/test-http-status-code.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Simple test of Node's HTTP ServerResponse.statusCode +// ServerResponse.prototype.statusCode + +var testsComplete = 0; +var tests = [200, 202, 300, 404, 500]; +var testIdx = 0; + +var s = http.createServer(function(req, res) { + var t = tests[testIdx]; + res.writeHead(t, {'Content-Type': 'text/plain'}); + console.log('--\nserver: statusCode after writeHead: ' + res.statusCode); + assert.equal(res.statusCode, t); + res.end('hello world\n'); +}); + +s.listen(common.PORT, nextTest); + + +function nextTest() { + if (testIdx + 1 === tests.length) { + return s.close(); + } + var test = tests[testIdx]; + + http.get({ port: common.PORT }, function(response) { + console.log('client: expected status: ' + test); + console.log('client: statusCode: ' + response.statusCode); + assert.equal(response.statusCode, test); + response.on('end', function() { + testsComplete++; + testIdx += 1; + nextTest(); + }); + response.resume(); + }); +} + + +process.on('exit', function() { + assert.equal(4, testsComplete); +}); + diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js new file mode 100644 index 000000000..a8d7a3510 --- /dev/null +++ b/test/parallel/test-http-status-message.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var s = http.createServer(function(req, res) { + res.statusCode = 200; + res.statusMessage = 'Custom Message'; + res.end(''); +}); + +s.listen(common.PORT, test); + + +function test() { + var bufs = []; + var client = net.connect(common.PORT, function() { + client.write('GET / HTTP/1.1\r\nConnection: close\r\n\r\n'); + }); + client.on('data', function(chunk) { + bufs.push(chunk); + }); + client.on('end', function() { + var head = Buffer.concat(bufs).toString('binary').split('\r\n')[0]; + assert.equal('HTTP/1.1 200 Custom Message', head); + console.log('ok'); + s.close(); + }); +} diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js new file mode 100644 index 000000000..3e62612b3 --- /dev/null +++ b/test/parallel/test-http-timeout-overflow.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var port = common.PORT; +var serverRequests = 0; +var clientRequests = 0; + +var server = http.createServer(function(req, res) { + serverRequests++; + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('OK'); +}); + +server.listen(port, function() { + function callback(){} + + var req = http.request({ + port: port, + path: '/', + agent: false + }, function(res) { + req.clearTimeout(callback); + + res.on('end', function() { + clientRequests++; + server.close(); + }) + + res.resume(); + }); + + // Overflow signed int32 + req.setTimeout(0xffffffff, callback); + req.end(); +}); + +process.once('exit', function() { + assert.equal(clientRequests, 1); + assert.equal(serverRequests, 1); +}); diff --git a/test/parallel/test-http-timeout.js b/test/parallel/test-http-timeout.js new file mode 100644 index 000000000..ddd01c8a8 --- /dev/null +++ b/test/parallel/test-http-timeout.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var port = common.PORT; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('OK'); +}); + +var agent = new http.Agent({maxSockets: 1}); + +server.listen(port, function() { + + for (var i = 0; i < 11; ++i) { + createRequest().end(); + } + + function callback(){} + + var count = 0; + + function createRequest() { + var req = http.request({port: port, path: '/', agent: agent}, function(res) { + + req.clearTimeout(callback); + + res.on('end', function() { + count++; + + if (count == 11) { + server.close(); + } + }) + + res.resume(); + }); + + req.setTimeout(1000, callback); + return req; + } +}); diff --git a/test/parallel/test-http-unix-socket.js b/test/parallel/test-http-unix-socket.js new file mode 100644 index 000000000..66d5403f6 --- /dev/null +++ b/test/parallel/test-http-unix-socket.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var http = require('http'); + +var status_ok = false; // status code == 200? +var headers_ok = false; +var body_ok = false; + +var server = http.createServer(function(req, res) { + res.writeHead(200, { + 'Content-Type': 'text/plain', + 'Connection': 'close' + }); + res.write('hello '); + res.write('world\n'); + res.end(); +}); + +server.listen(common.PIPE, function() { + + var options = { + socketPath: common.PIPE, + path: '/' + }; + + var req = http.get(options, function(res) { + assert.equal(res.statusCode, 200); + status_ok = true; + + assert.equal(res.headers['content-type'], 'text/plain'); + headers_ok = true; + + res.body = ''; + res.setEncoding('utf8'); + + res.on('data', function(chunk) { + res.body += chunk; + }); + + res.on('end', function() { + assert.equal(res.body, 'hello world\n'); + body_ok = true; + server.close(function(error) { + assert.equal(error, undefined); + server.close(function(error) { + assert.equal(error && error.message, 'Not running'); + }); + }); + }); + }); + + req.on('error', function(e) { + console.log(e.stack); + process.exit(1); + }); + + req.end(); + +}); + +process.on('exit', function() { + assert.ok(status_ok); + assert.ok(headers_ok); + assert.ok(body_ok); +}); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js new file mode 100644 index 000000000..1077a983d --- /dev/null +++ b/test/parallel/test-http-upgrade-agent.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to +// the HTTP client. This test uses a raw TCP server to better control server +// behavior. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +// Create a TCP server +var srv = net.createServer(function(c) { + var data = ''; + c.on('data', function(d) { + data += d.toString('utf8'); + + c.write('HTTP/1.1 101\r\n'); + c.write('hello: world\r\n'); + c.write('connection: upgrade\r\n'); + c.write('upgrade: websocket\r\n'); + c.write('\r\n'); + c.write('nurtzo'); + }); + + c.on('end', function() { + c.end(); + }); +}); + +var gotUpgrade = false; + +srv.listen(common.PORT, '127.0.0.1', function() { + + var options = { + port: common.PORT, + host: '127.0.0.1', + headers: { + 'upgrade': 'websocket' + } + }; + var name = options.host + ':' + options.port; + + var req = http.request(options); + req.end(); + + req.on('upgrade', function(res, socket, upgradeHead) { + // XXX: This test isn't fantastic, as it assumes that the entire response + // from the server will arrive in a single data callback + assert.equal(upgradeHead, 'nurtzo'); + + console.log(res.headers); + var expectedHeaders = { 'hello': 'world', + 'connection': 'upgrade', + 'upgrade': 'websocket' }; + assert.deepEqual(expectedHeaders, res.headers); + + // Make sure this request got removed from the pool. + assert(!http.globalAgent.sockets.hasOwnProperty(name)); + + req.on('close', function() { + socket.end(); + srv.close(); + + gotUpgrade = true; + }); + }); + +}); + +process.on('exit', function() { + assert.ok(gotUpgrade); +}); diff --git a/test/parallel/test-http-upgrade-client.js b/test/parallel/test-http-upgrade-client.js new file mode 100644 index 000000000..3bf5beccf --- /dev/null +++ b/test/parallel/test-http-upgrade-client.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to +// the HTTP client. This test uses a raw TCP server to better control server +// behavior. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); +var net = require('net'); + +// Create a TCP server +var srv = net.createServer(function(c) { + var data = ''; + c.on('data', function(d) { + data += d.toString('utf8'); + + c.write('HTTP/1.1 101\r\n'); + c.write('hello: world\r\n'); + c.write('connection: upgrade\r\n'); + c.write('upgrade: websocket\r\n'); + c.write('\r\n'); + c.write('nurtzo'); + }); + + c.on('end', function() { + c.end(); + }); +}); + +var gotUpgrade = false; + +srv.listen(common.PORT, '127.0.0.1', function() { + + var req = http.get({ port: common.PORT }); + req.on('upgrade', function(res, socket, upgradeHead) { + // XXX: This test isn't fantastic, as it assumes that the entire response + // from the server will arrive in a single data callback + assert.equal(upgradeHead, 'nurtzo'); + + console.log(res.headers); + var expectedHeaders = {'hello': 'world', + 'connection': 'upgrade', + 'upgrade': 'websocket' }; + assert.deepEqual(expectedHeaders, res.headers); + + socket.end(); + srv.close(); + + gotUpgrade = true; + }); +}); + +process.on('exit', function() { + assert.ok(gotUpgrade); +}); diff --git a/test/parallel/test-http-upgrade-client2.js b/test/parallel/test-http-upgrade-client2.js new file mode 100644 index 000000000..fa39f2a57 --- /dev/null +++ b/test/parallel/test-http-upgrade-client2.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var CRLF = '\r\n'; + +var server = http.createServer(); +server.on('upgrade', function(req, socket, head) { + socket.write('HTTP/1.1 101 Ok' + CRLF + + 'Connection: Upgrade' + CRLF + + 'Upgrade: Test' + CRLF + CRLF + 'head'); + socket.on('end', function() { + socket.end(); + }); +}); + +var successCount = 0; + +server.listen(common.PORT, function() { + + function upgradeRequest(fn) { + console.log('req'); + var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; + var request = http.request({ port: common.PORT, headers: header }); + var wasUpgrade = false; + + function onUpgrade(res, socket, head) { + console.log('client upgraded'); + wasUpgrade = true; + + request.removeListener('upgrade', onUpgrade); + socket.end(); + } + request.on('upgrade', onUpgrade); + + function onEnd() { + console.log('client end'); + request.removeListener('end', onEnd); + if (!wasUpgrade) { + throw new Error('hasn\'t received upgrade event'); + } else { + fn && process.nextTick(fn); + } + } + request.on('close', onEnd); + + request.write('head'); + + } + + upgradeRequest(function() { + successCount++; + upgradeRequest(function() { + successCount++; + // Test pass + console.log('Pass!'); + server.close(); + }); + }); + +}); + +process.on('exit', function() { + assert.equal(2, successCount); +}); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js new file mode 100644 index 000000000..b514eff3c --- /dev/null +++ b/test/parallel/test-http-upgrade-server.js @@ -0,0 +1,185 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var util = require('util'); +var net = require('net'); +var http = require('http'); + + +var requests_recv = 0; +var requests_sent = 0; +var request_upgradeHead = null; + +function createTestServer() { + return new testServer(); +} + +function testServer() { + var server = this; + http.Server.call(server, function() {}); + + server.on('connection', function() { + requests_recv++; + }); + + server.on('request', function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('okay'); + res.end(); + }); + + server.on('upgrade', function(req, socket, upgradeHead) { + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n\r\n'); + + request_upgradeHead = upgradeHead; + + socket.on('data', function(d) { + var data = d.toString('utf8'); + if (data == 'kill') { + socket.end(); + } else { + socket.write(data, 'utf8'); + } + }); + }); +} + +util.inherits(testServer, http.Server); + + +function writeReq(socket, data, encoding) { + requests_sent++; + socket.write(data); +} + + +/*----------------------------------------------- + connection: Upgrade with listener +-----------------------------------------------*/ +function test_upgrade_with_listener(_server) { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + var state = 0; + + conn.on('connect', function() { + writeReq(conn, + 'GET / HTTP/1.1\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n' + + 'WjN}|M(6'); + }); + + conn.on('data', function(data) { + state++; + + assert.equal('string', typeof data); + + if (state == 1) { + assert.equal('HTTP/1.1 101', data.substr(0, 12)); + assert.equal('WjN}|M(6', request_upgradeHead.toString('utf8')); + conn.write('test', 'utf8'); + } else if (state == 2) { + assert.equal('test', data); + conn.write('kill', 'utf8'); + } + }); + + conn.on('end', function() { + assert.equal(2, state); + conn.end(); + _server.removeAllListeners('upgrade'); + test_upgrade_no_listener(); + }); +} + +/*----------------------------------------------- + connection: Upgrade, no listener +-----------------------------------------------*/ +var test_upgrade_no_listener_ended = false; + +function test_upgrade_no_listener() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + + conn.on('connect', function() { + writeReq(conn, + 'GET / HTTP/1.1\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n'); + }); + + conn.on('end', function() { + test_upgrade_no_listener_ended = true; + conn.end(); + }); + + conn.on('close', function() { + test_standard_http(); + }); +} + +/*----------------------------------------------- + connection: normal +-----------------------------------------------*/ +function test_standard_http() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + + conn.on('connect', function() { + writeReq(conn, 'GET / HTTP/1.1\r\n\r\n'); + }); + + conn.once('data', function(data) { + assert.equal('string', typeof data); + assert.equal('HTTP/1.1 200', data.substr(0, 12)); + conn.end(); + }); + + conn.on('close', function() { + server.close(); + }); +} + + +var server = createTestServer(); + +server.listen(common.PORT, function() { + // All tests get chained after this: + test_upgrade_with_listener(server); +}); + + +/*----------------------------------------------- + Fin. +-----------------------------------------------*/ +process.on('exit', function() { + assert.equal(3, requests_recv); + assert.equal(3, requests_sent); + assert.ok(test_upgrade_no_listener_ended); +}); diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js new file mode 100644 index 000000000..e617d3b1c --- /dev/null +++ b/test/parallel/test-http-upgrade-server2.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var server = http.createServer(function(req, res) { + common.error('got req'); + throw new Error('This shouldn\'t happen.'); +}); + +server.on('upgrade', function(req, socket, upgradeHead) { + common.error('got upgrade event'); + // test that throwing an error from upgrade gets + // is uncaught + throw new Error('upgrade error'); +}); + +var gotError = false; + +process.on('uncaughtException', function(e) { + common.error('got \'clientError\' event'); + assert.equal('upgrade error', e.message); + gotError = true; + process.exit(0); +}); + + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('connect', function() { + common.error('client wrote message'); + c.write('GET /blah HTTP/1.1\r\n' + + 'Upgrade: WebSocket\r\n' + + 'Connection: Upgrade\r\n' + + '\r\n\r\nhello world'); + }); + + c.on('end', function() { + c.end(); + }); + + c.on('close', function() { + common.error('client close'); + server.close(); + }); +}); + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/test/parallel/test-http-url.parse-auth-with-header-in-request.js b/test/parallel/test-http-url.parse-auth-with-header-in-request.js new file mode 100644 index 000000000..5ac789068 --- /dev/null +++ b/test/parallel/test-http-url.parse-auth-with-header-in-request.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var testURL = url.parse('http://asdf:qwer@localhost:' + common.PORT); +// the test here is if you set a specific authorization header in the +// request we should not override that with basic auth +testURL.headers = { + Authorization: 'NoAuthForYOU' +}; + +function check(request) { + // the correct authorization header is be passed + assert.strictEqual(request.headers.authorization, 'NoAuthForYOU'); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/test/parallel/test-http-url.parse-auth.js b/test/parallel/test-http-url.parse-auth.js new file mode 100644 index 000000000..4c07d5ffc --- /dev/null +++ b/test/parallel/test-http-url.parse-auth.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +// username = "user", password = "pass:" +var testURL = url.parse('http://user:pass%3A@localhost:' + common.PORT); + +function check(request) { + // the correct authorization header is be passed + assert.strictEqual(request.headers.authorization, 'Basic dXNlcjpwYXNzOg=='); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/test/parallel/test-http-url.parse-basic.js b/test/parallel/test-http-url.parse-basic.js new file mode 100644 index 000000000..8bf12b1c2 --- /dev/null +++ b/test/parallel/test-http-url.parse-basic.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT); + +// make sure the basics work +function check(request) { + // default method should still be get + assert.strictEqual(request.method, 'GET'); + // there are no URL params, so you should not see any + assert.strictEqual(request.url, '/'); + // the host header should use the url.parse.hostname + assert.strictEqual(request.headers.host, + testURL.hostname + ':' + testURL.port); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + var clientRequest = http.request(testURL); + // since there is a little magic with the agent + // make sure that an http request uses the http.Agent + assert.ok(clientRequest.agent instanceof http.Agent); + clientRequest.end(); +}); diff --git a/test/parallel/test-http-url.parse-https.request.js b/test/parallel/test-http-url.parse-https.request.js new file mode 100644 index 000000000..b83f0df9f --- /dev/null +++ b/test/parallel/test-http-url.parse-https.request.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var url = require('url'); +var fs = require('fs'); +var clientRequest; + +// https options +var httpsOptions = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var testURL = url.parse('https://localhost:' + common.PORT); +testURL.rejectUnauthorized = false; + +function check(request) { + // assert that I'm https + assert.ok(request.socket._secureEstablished); +} + +var server = https.createServer(httpsOptions, function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + var clientRequest = https.request(testURL); + // since there is a little magic with the agent + // make sure that the request uses the https.Agent + assert.ok(clientRequest.agent instanceof https.Agent); + clientRequest.end(); +}); diff --git a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js new file mode 100644 index 000000000..0f5712641 --- /dev/null +++ b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js @@ -0,0 +1,82 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + + +assert.throws(function() { + http.request(url.parse('file:///whatever')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol "file:" not supported. Expected "http:".'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('mailto:asdf@asdf.com')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol "mailto:" not supported. Expected "http:".'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('ftp://www.example.com')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol "ftp:" not supported. Expected "http:".'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('javascript:alert(\'hello\');')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol "javascript:" not supported. Expected "http:".'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('xmpp:isaacschlueter@jabber.org')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol "xmpp:" not supported. Expected "http:".'); + return true; + } +}); + +assert.throws(function() { + http.request(url.parse('f://some.host/path')); +}, function(err) { + if (err instanceof Error) { + assert.strictEqual(err.message, 'Protocol "f:" not supported. Expected "http:".'); + return true; + } +}); + +//TODO do I need to test url.parse(notPrococol.example.com)? diff --git a/test/parallel/test-http-url.parse-path.js b/test/parallel/test-http-url.parse-path.js new file mode 100644 index 000000000..8ef09520c --- /dev/null +++ b/test/parallel/test-http-url.parse-path.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT + '/asdf'); + +function check(request) { + // a path should come over + assert.strictEqual(request.url, '/asdf'); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/test/parallel/test-http-url.parse-post.js b/test/parallel/test-http-url.parse-post.js new file mode 100644 index 000000000..be93166d5 --- /dev/null +++ b/test/parallel/test-http-url.parse-post.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); +testURL.method = 'POST'; + +function check(request) { + //url.parse should not mess with the method + assert.strictEqual(request.method, 'POST'); + //everything else should be right + assert.strictEqual(request.url, '/asdf?qwer=zxcv'); + //the host header should use the url.parse.hostname + assert.strictEqual(request.headers.host, + testURL.hostname + ':' + testURL.port); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/test/parallel/test-http-url.parse-search.js b/test/parallel/test-http-url.parse-search.js new file mode 100644 index 000000000..3b6727d0b --- /dev/null +++ b/test/parallel/test-http-url.parse-search.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); + +function check(request) { + // a path should come over with params + assert.strictEqual(request.url, '/asdf?qwer=zxcv'); +} + +var server = http.createServer(function(request, response) { + // run the check function + check.call(this, request, response); + response.writeHead(200, {}); + response.end('ok'); + server.close(); +}); + +server.listen(common.PORT, function() { + // make the request + http.request(testURL).end(); +}); diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js new file mode 100644 index 000000000..b6cf7d8be --- /dev/null +++ b/test/parallel/test-http-wget.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var http = require('http'); + +// wget sends an HTTP/1.0 request with Connection: Keep-Alive +// +// Sending back a chunked response to an HTTP/1.0 client would be wrong, +// so what has to happen in this case is that the connection is closed +// by the server after the entity body if the Content-Length was not +// sent. +// +// If the Content-Length was sent, we can probably safely honor the +// keep-alive request, even though HTTP 1.0 doesn't say that the +// connection can be kept open. Presumably any client sending this +// header knows that it is extending HTTP/1.0 and can handle the +// response. We don't test that here however, just that if the +// content-length is not provided, that the connection is in fact +// closed. + +var server_response = ''; +var client_got_eof = false; +var connection_was_closed = false; + +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello '); + res.write('world\n'); + res.end(); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var c = net.createConnection(common.PORT); + + c.setEncoding('utf8'); + + c.on('connect', function() { + c.write('GET / HTTP/1.0\r\n' + + 'Connection: Keep-Alive\r\n\r\n'); + }); + + c.on('data', function(chunk) { + console.log(chunk); + server_response += chunk; + }); + + c.on('end', function() { + client_got_eof = true; + console.log('got end'); + c.end(); + }); + + c.on('close', function() { + connection_was_closed = true; + console.log('got close'); + server.close(); + }); +}); + +process.on('exit', function() { + var m = server_response.split('\r\n\r\n'); + assert.equal(m[1], 'hello world\n'); + assert.ok(client_got_eof); + assert.ok(connection_was_closed); +}); diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js new file mode 100644 index 000000000..3a740ae5b --- /dev/null +++ b/test/parallel/test-http-write-callbacks.js @@ -0,0 +1,100 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var serverEndCb = false; +var serverIncoming = ''; +var serverIncomingExpect = 'bazquuxblerg'; + +var clientEndCb = false; +var clientIncoming = ''; +var clientIncomingExpect = 'asdffoobar'; + +process.on('exit', function() { + assert(serverEndCb); + assert.equal(serverIncoming, serverIncomingExpect); + assert(clientEndCb); + assert.equal(clientIncoming, clientIncomingExpect); + console.log('ok'); +}); + +// Verify that we get a callback when we do res.write(..., cb) +var server = http.createServer(function(req, res) { + res.statusCode = 400; + res.end('Bad Request.\nMust send Expect:100-continue\n'); +}); + +server.on('checkContinue', function(req, res) { + server.close(); + assert.equal(req.method, 'PUT'); + res.writeContinue(function() { + // continue has been written + req.on('end', function() { + res.write('asdf', function(er) { + assert.ifError(er); + res.write('foo', 'ascii', function(er) { + assert.ifError(er); + res.end(new Buffer('bar'), 'buffer', function(er) { + serverEndCb = true; + }); + }); + }); + }); + }); + + req.setEncoding('ascii'); + req.on('data', function(c) { + serverIncoming += c; + }); +}); + +server.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + method: 'PUT', + headers: { 'expect': '100-continue' } + }); + req.on('continue', function() { + // ok, good to go. + req.write('YmF6', 'base64', function(er) { + assert.ifError(er); + req.write(new Buffer('quux'), function(er) { + assert.ifError(er); + req.end('626c657267', 'hex', function(er) { + assert.ifError(er); + clientEndCb = true; + }); + }); + }); + }); + req.on('response', function(res) { + // this should not come until after the end is flushed out + assert(clientEndCb); + res.setEncoding('ascii'); + res.on('data', function(c) { + clientIncoming += c; + }); + }); +}); diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js new file mode 100644 index 000000000..baf9c27f4 --- /dev/null +++ b/test/parallel/test-http-write-empty-string.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var server = http.createServer(function(request, response) { + console.log('responding to ' + request.url); + + response.writeHead(200, {'Content-Type': 'text/plain'}); + response.write('1\n'); + response.write(''); + response.write('2\n'); + response.write(''); + response.end('3\n'); + + this.close(); +}); + +var response = ''; + +process.on('exit', function() { + assert.equal('1\n2\n3\n', response); +}); + + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + assert.equal(200, res.statusCode); + res.setEncoding('ascii'); + res.on('data', function(chunk) { + response += chunk; + }); + common.error('Got /hello response'); + }); +}); + diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js new file mode 100644 index 000000000..88923ef27 --- /dev/null +++ b/test/parallel/test-http-write-head.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +// Verify that ServerResponse.writeHead() works as setHeader. +// Issue 5036 on github. + +var s = http.createServer(function(req, res) { + res.setHeader('test', '1'); + + // toLowerCase() is used on the name argument, so it must be a string. + var threw = false; + try { + res.setHeader(0xf00, 'bar'); + } catch (e) { + assert.ok(e instanceof TypeError); + threw = true; + } + assert.ok(threw, 'Non-string names should throw'); + + res.writeHead(200, { Test: '2' }); + res.end(); +}); + +s.listen(common.PORT, runTest); + +function runTest() { + http.get({ port: common.PORT }, function(response) { + response.on('end', function() { + assert.equal(response.headers['test'], '2'); + assert(response.rawHeaders.indexOf('Test') !== -1); + s.close(); + }); + response.resume(); + }); +} diff --git a/test/parallel/test-http-zero-length-write.js b/test/parallel/test-http-zero-length-write.js new file mode 100644 index 000000000..e68f947c3 --- /dev/null +++ b/test/parallel/test-http-zero-length-write.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var http = require('http'); + +var Stream = require('stream'); + +function getSrc() { + // An old-style readable stream. + // The Readable class prevents this behavior. + var src = new Stream(); + + // start out paused, just so we don't miss anything yet. + var paused = false; + src.pause = function() { + paused = true; + }; + src.resume = function() { + paused = false; + }; + + var chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; + var interval = setInterval(function() { + if (paused) + return + + var chunk = chunks.shift(); + if (chunk !== undefined) { + src.emit('data', chunk); + } else { + src.emit('end'); + clearInterval(interval); + } + }, 1); + + return src; +} + + +var expect = 'asdffoobar'; + +var server = http.createServer(function(req, res) { + var actual = ''; + req.setEncoding('utf8'); + req.on('data', function(c) { + actual += c; + }); + req.on('end', function() { + assert.equal(actual, expect); + getSrc().pipe(res); + }); + server.close(); +}); + +server.listen(common.PORT, function() { + var req = http.request({ port: common.PORT, method: 'POST' }); + var actual = ''; + req.on('response', function(res) { + res.setEncoding('utf8'); + res.on('data', function(c) { + actual += c; + }); + res.on('end', function() { + assert.equal(actual, expect); + }); + }); + getSrc().pipe(req); +}); + +process.on('exit', function(c) { + if (!c) console.log('ok'); +}); diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js new file mode 100644 index 000000000..fa388356d --- /dev/null +++ b/test/parallel/test-http.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var url = require('url'); + +function p(x) { + common.error(common.inspect(x)); +} + +var responses_sent = 0; +var responses_recvd = 0; +var body0 = ''; +var body1 = ''; + +var server = http.Server(function(req, res) { + if (responses_sent == 0) { + assert.equal('GET', req.method); + assert.equal('/hello', url.parse(req.url).pathname); + + console.dir(req.headers); + assert.equal(true, 'accept' in req.headers); + assert.equal('*/*', req.headers['accept']); + + assert.equal(true, 'foo' in req.headers); + assert.equal('bar', req.headers['foo']); + } + + if (responses_sent == 1) { + assert.equal('POST', req.method); + assert.equal('/world', url.parse(req.url).pathname); + this.close(); + } + + req.on('end', function() { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('The path was ' + url.parse(req.url).pathname); + res.end(); + responses_sent += 1; + }); + req.resume(); + + //assert.equal('127.0.0.1', res.connection.remoteAddress); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var agent = new http.Agent({ port: common.PORT, maxSockets: 1 }); + http.get({ + port: common.PORT, + path: '/hello', + headers: {'Accept': '*/*', 'Foo': 'bar'}, + agent: agent + }, function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body0 += chunk; }); + common.debug('Got /hello response'); + }); + + setTimeout(function() { + var req = http.request({ + port: common.PORT, + method: 'POST', + path: '/world', + agent: agent + }, function(res) { + assert.equal(200, res.statusCode); + responses_recvd += 1; + res.setEncoding('utf8'); + res.on('data', function(chunk) { body1 += chunk; }); + common.debug('Got /world response'); + }); + req.end(); + }, 1); +}); + +process.on('exit', function() { + common.debug('responses_recvd: ' + responses_recvd); + assert.equal(2, responses_recvd); + + common.debug('responses_sent: ' + responses_sent); + assert.equal(2, responses_sent); + + assert.equal('The path was /hello', body0); + assert.equal('The path was /world', body1); +}); + diff --git a/test/parallel/test-https-agent.js b/test/parallel/test-https-agent.js new file mode 100644 index 000000000..34fa15c73 --- /dev/null +++ b/test/parallel/test-https-agent.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + + +var server = https.Server(options, function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + + +var responses = 0; +var N = 10; +var M = 10; + +server.listen(common.PORT, function() { + for (var i = 0; i < N; i++) { + setTimeout(function() { + for (var j = 0; j < M; j++) { + https.get({ + path: '/', + port: common.PORT, + rejectUnauthorized: false + }, function(res) { + res.resume(); + console.log(res.statusCode); + if (++responses == N * M) server.close(); + }).on('error', function(e) { + console.log(e.message); + process.exit(1); + }); + } + }, i); + } +}); + + +process.on('exit', function() { + assert.equal(N * M, responses); +}); diff --git a/test/parallel/test-https-byteswritten.js b/test/parallel/test-https-byteswritten.js new file mode 100644 index 000000000..21c300efa --- /dev/null +++ b/test/parallel/test-https-byteswritten.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var http = require('http'); +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var body = 'hello world\n'; + +var httpsServer = https.createServer(options, function(req, res) { + res.on('finish', function() { + assert(typeof(req.connection.bytesWritten) === 'number'); + assert(req.connection.bytesWritten > 0); + httpsServer.close(); + console.log('ok'); + }); + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end(body); +}); + +httpsServer.listen(common.PORT, function() { + https.get({ + port: common.PORT, + rejectUnauthorized: false + }); +}); diff --git a/test/parallel/test-https-client-checkServerIdentity.js b/test/parallel/test-https-client-checkServerIdentity.js new file mode 100644 index 000000000..a985d23e5 --- /dev/null +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-cert.pem')) +}; + +var reqCount = 0; + +var server = https.createServer(options, function (req, res) { + ++reqCount; + res.writeHead(200); + res.end(); + req.resume(); +}).listen(common.PORT, function () { + authorized(); +}); + +function authorized() { + var req = https.request({ + port: common.PORT, + rejectUnauthorized: true, + ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] + }, function (res) { + assert(false); + }); + req.on('error', function (err) { + override(); + }); + req.end(); +} + +function override() { + var options = { + port: common.PORT, + rejectUnauthorized: true, + ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))], + checkServerIdentity: function (host, cert) { + return false; + } + }; + options.agent = new https.Agent(options); + var req = https.request(options, function (res) { + assert(req.socket.authorized); + server.close(); + }); + req.on('error', function (err) { + throw err; + }); + req.end(); +} + +process.on('exit', function () { + assert.equal(reqCount, 1); +}); diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js new file mode 100644 index 000000000..ae5613c14 --- /dev/null +++ b/test/parallel/test-https-client-get-url.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +// disable strict server certificate validation by the client +process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var seen_req = false; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = https.createServer(options, function(req, res) { + assert.equal('GET', req.method); + assert.equal('/foo?bar', req.url); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello\n'); + res.end(); + server.close(); + seen_req = true; +}); + +server.listen(common.PORT, function() { + https.get('https://127.0.0.1:' + common.PORT + '/foo?bar'); +}); + +process.on('exit', function() { + assert(seen_req); +}); diff --git a/test/parallel/test-https-client-reject.js b/test/parallel/test-https-client-reject.js new file mode 100644 index 000000000..bf191da1d --- /dev/null +++ b/test/parallel/test-https-client-reject.js @@ -0,0 +1,97 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var reqCount = 0; + +var server = https.createServer(options, function(req, res) { + ++reqCount; + res.writeHead(200); + res.end(); + req.resume(); +}).listen(common.PORT, function() { + unauthorized(); +}); + +function unauthorized() { + var req = https.request({ + port: common.PORT, + rejectUnauthorized: false + }, function(res) { + assert(!req.socket.authorized); + res.resume(); + rejectUnauthorized(); + }); + req.on('error', function(err) { + throw err; + }); + req.end(); +} + +function rejectUnauthorized() { + var options = { + port: common.PORT + }; + options.agent = new https.Agent(options); + var req = https.request(options, function(res) { + assert(false); + }); + req.on('error', function(err) { + authorized(); + }); + req.end(); +} + +function authorized() { + var options = { + port: common.PORT, + ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] + }; + options.agent = new https.Agent(options); + var req = https.request(options, function(res) { + res.resume(); + assert(req.socket.authorized); + server.close(); + }); + req.on('error', function(err) { + assert(false); + }); + req.end(); +} + +process.on('exit', function() { + assert.equal(reqCount, 2); +}); diff --git a/test/parallel/test-https-client-resume.js b/test/parallel/test-https-client-resume.js new file mode 100644 index 000000000..0433afdd9 --- /dev/null +++ b/test/parallel/test-https-client-resume.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Create an ssl server. First connection, validate that not resume. +// Cache session and close connection. Use session on second connection. +// ASSERT resumption. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; + +// create server +var server = https.createServer(options, function(res, res) { + res.end('Goodbye'); + connections++; +}); + +// start listening +server.listen(common.PORT, function() { + + var session1 = null; + var client1 = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + console.log('connect1'); + assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); + session1 = client1.getSession(); + client1.write('GET / HTTP/1.0\r\n' + + 'Server: 127.0.0.1\r\n' + + '\r\n'); + }); + + client1.on('close', function() { + console.log('close1'); + + var opts = { + port: common.PORT, + rejectUnauthorized: false, + session: session1 + }; + + var client2 = tls.connect(opts, function() { + console.log('connect2'); + assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); + client2.write('GET / HTTP/1.0\r\n' + + 'Server: 127.0.0.1\r\n' + + '\r\n'); + }); + + client2.on('close', function() { + console.log('close2'); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(2, connections); +}); diff --git a/test/parallel/test-https-connecting-to-http.js b/test/parallel/test-https-connecting-to-http.js new file mode 100644 index 000000000..50bb2a8a3 --- /dev/null +++ b/test/parallel/test-https-connecting-to-http.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This tests the situation where you try to connect a https client +// to an http server. You should get an error and exit. +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var http = require('http'); + + +var reqCount = 0; +var resCount = 0; +var reqErrorCount = 0; +var body = 'hello world\n'; + + +var server = http.createServer(function(req, res) { + reqCount++; + console.log('got request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server.listen(common.PORT, function() { + var req = https.get({ port: common.PORT }, function(res) { + resCount++; + }); + + req.on('error', function(e) { + console.log('Got expected error: ', e.message); + server.close(); + reqErrorCount++; + }); +}); + + +process.on('exit', function() { + assert.equal(0, reqCount); + assert.equal(0, resCount); + assert.equal(1, reqErrorCount); +}); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js new file mode 100644 index 000000000..5509a2474 --- /dev/null +++ b/test/parallel/test-https-drain.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var bufSize = 1024 * 1024; +var sent = 0; +var received = 0; + +var server = https.createServer(options, function(req, res) { + res.writeHead(200); + req.pipe(res); +}); + +server.listen(common.PORT, function() { + var resumed = false; + var req = https.request({ + method: 'POST', + port: common.PORT, + rejectUnauthorized: false + }, function(res) { + var timer; + res.pause(); + common.debug('paused'); + send(); + function send() { + if (req.write(new Buffer(bufSize))) { + sent += bufSize; + assert.ok(sent < 100 * 1024 * 1024); // max 100MB + return process.nextTick(send); + } + sent += bufSize; + common.debug('sent: ' + sent); + resumed = true; + res.resume(); + common.debug('resumed'); + timer = setTimeout(function() { + process.exit(1); + }, 1000); + } + + res.on('data', function(data) { + assert.ok(resumed); + if (timer) { + clearTimeout(timer); + timer = null; + } + received += data.length; + if (received >= sent) { + common.debug('received: ' + received); + req.end(); + server.close(); + } + }); + }); + req.write('a'); + ++sent; +}); + +process.on('exit', function() { + assert.equal(sent, received); +}); diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js new file mode 100644 index 000000000..7a465b865 --- /dev/null +++ b/test/parallel/test-https-eof-for-eom.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// I hate HTTP. One way of terminating an HTTP response is to not send +// a content-length header, not send a transfer-encoding: chunked header, +// and simply terminate the TCP connection. That is identity +// transfer-encoding. +// +// This test is to be sure that the https client is handling this case +// correctly. +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var https = require('https'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + + +var server = tls.Server(options, function(socket) { + console.log('2) Server got request'); + socket.write('HTTP/1.1 200 OK\r\n' + + 'Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n' + + 'Expires: -1\r\n' + + 'Cache-Control: private, max-age=0\r\n' + + 'Set-Cookie: xyz\r\n' + + 'Set-Cookie: abc\r\n' + + 'Server: gws\r\n' + + 'X-XSS-Protection: 1; mode=block\r\n' + + 'Connection: close\r\n' + + '\r\n'); + + socket.write('hello world\n'); + + setTimeout(function() { + socket.end('hello world\n'); + console.log('4) Server finished response'); + }, 100); +}); + + +var gotHeaders = false; +var gotEnd = false; +var bodyBuffer = ''; + +server.listen(common.PORT, function() { + console.log('1) Making Request'); + var req = https.get({ + port: common.PORT, + rejectUnauthorized: false + }, function(res) { + server.close(); + console.log('3) Client got response headers.'); + + assert.equal('gws', res.headers.server); + gotHeaders = true; + + res.setEncoding('utf8'); + res.on('data', function(s) { + bodyBuffer += s; + }); + + res.on('end', function() { + console.log('5) Client got "end" event.'); + gotEnd = true; + }); + }); +}); + +process.on('exit', function() { + assert.ok(gotHeaders); + assert.ok(gotEnd); + assert.equal('hello world\nhello world\n', bodyBuffer); +}); + diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js new file mode 100644 index 000000000..c9fc746e8 --- /dev/null +++ b/test/parallel/test-https-foafssl.js @@ -0,0 +1,99 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var join = require('path').join; + +var fs = require('fs'); +var spawn = require('child_process').spawn; + +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/agent.key'), + cert: fs.readFileSync(common.fixturesDir + '/agent.crt'), + requestCert: true +}; + +var reqCount = 0; +var CRLF = '\r\n'; +var body = 'hello world\n'; +var cert; +var subjectaltname; +var modulus; +var exponent; + +var server = https.createServer(options, function(req, res) { + reqCount++; + console.log('got request'); + + cert = req.connection.getPeerCertificate(); + + subjectaltname = cert.subjectaltname; + modulus = cert.modulus; + exponent = cert.exponent; + + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + +server.listen(common.PORT, function() { + var args = ['s_client', + '-quiet', + '-connect', '127.0.0.1:' + common.PORT, + '-cert', join(common.fixturesDir, 'foafssl.crt'), + '-key', join(common.fixturesDir, 'foafssl.key')]; + + var client = spawn(common.opensslCli, args); + + client.stdout.on('data', function(data) { + var message = data.toString(); + var contents = message.split(CRLF + CRLF).pop(); + assert.equal(body, contents); + server.close(); + }); + + client.stdin.write('GET /\n\n'); + + client.on('error', function(error) { + throw error; + }); +}); + +process.on('exit', function() { + assert.equal(subjectaltname, 'URI:http://example.com/#me'); + assert.equal(modulus, 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09' + + 'BBC3A5519F349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C2896' + + '4694B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560CDE9C13' + + '455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06AFF8BE191B7920' + + 'DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF82100B03A4F0FF1809278E4DD' + + 'FDA7DE954ED56DC7AD9A47EEBC37D771A366FC60A5BCB72373BEC180649B3EFA0E90' + + '92707210B41B90032BB18BC91F2046EBDAF1191F4A4E26D71879C4C7867B62FCD508' + + 'E8CE66E82D128A71E915809FCF44E8DE774067F1DE5D70B9C03687'); + assert.equal(exponent, '10001'); +}); diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js new file mode 100644 index 000000000..0c4f8da4c --- /dev/null +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var invalidLocalAddress = '1.2.3.4'; +var gotError = false; + +var server = https.createServer(options, function(req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); + req.resume(); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var req = https.request({ + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: invalidLocalAddress + }, function(res) { + assert.fail('unexpectedly got response from server'); + }).on('error', function(e) { + console.log('client got error: ' + e.message); + gotError = true; + server.close(); + }).end(); +}); + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/test/parallel/test-https-localaddress.js b/test/parallel/test-https-localaddress.js new file mode 100644 index 000000000..f703d41ae --- /dev/null +++ b/test/parallel/test-https-localaddress.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var https = require('https'), + fs = require('fs'), + assert = require('assert'); + +if (['linux', 'win32'].indexOf(process.platform) == -1) { + console.log('Skipping platform-specific test.'); + process.exit(); +} + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = https.createServer(options, function (req, res) { + console.log("Connect from: " + req.connection.remoteAddress); + assert.equal('127.0.0.2', req.connection.remoteAddress); + + req.on('end', function() { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('You are from: ' + req.connection.remoteAddress); + }); + req.resume(); +}); + +server.listen(common.PORT, "127.0.0.1", function() { + var options = { + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + localAddress: '127.0.0.2', + rejectUnauthorized: false + }; + + var req = https.request(options, function(res) { + res.on('end', function() { + server.close(); + process.exit(); + }); + res.resume(); + }); + req.end(); +}); diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js new file mode 100644 index 000000000..9da1ff8ee --- /dev/null +++ b/test/parallel/test-https-pfx.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var fs = require('fs'); + +var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); + +var options = { + host: '127.0.0.1', + port: common.PORT, + path: '/', + pfx: pfx, + passphrase: 'sample', + requestCert: true, + rejectUnauthorized: false +}; + +var server = https.createServer(options, function(req, res) { + assert.equal(req.socket.authorized, false); // not a client cert + assert.equal(req.socket.authorizationError, 'DEPTH_ZERO_SELF_SIGNED_CERT'); + res.writeHead(200); + res.end('OK'); +}); + +server.listen(options.port, options.host, function() { + var data = ''; + + https.get(options, function(res) { + res.on('data', function(data_) { data += data_ }); + res.on('end', function() { server.close() }); + }); + + process.on('exit', function() { + assert.equal(data, 'OK'); + }); +}); diff --git a/test/parallel/test-https-req-split.js b/test/parallel/test-https-req-split.js new file mode 100644 index 000000000..db54d7237 --- /dev/null +++ b/test/parallel/test-https-req-split.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +// disable strict server certificate validation by the client +process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var tls = require('tls'); +var fs = require('fs'); + +var seen_req = false; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +// Force splitting incoming data +tls.SLAB_BUFFER_SIZE = 1; + +var server = https.createServer(options); +server.on('upgrade', function(req, socket, upgrade) { + socket.on('data', function(data) { + throw new Error('Unexpected data: ' + data); + }); + socket.end('HTTP/1.1 200 Ok\r\n\r\n'); + seen_req = true; +}); + +server.listen(common.PORT, function() { + var req = https.request({ + host: '127.0.0.1', + port: common.PORT, + agent: false, + headers: { + Connection: 'Upgrade', + Upgrade: 'Websocket' + } + }, function() { + req.socket.destroy(); + server.close(); + }); + + req.end(); +}); + +process.on('exit', function() { + assert(seen_req); + console.log('ok'); +}); diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js new file mode 100644 index 000000000..e4dc1e360 --- /dev/null +++ b/test/parallel/test-https-set-timeout-server.js @@ -0,0 +1,208 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var https = require('https'); +var tls = require('tls'); +var fs = require('fs'); + +var tests = []; + +var serverOptions = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +function test(fn) { + if (!tests.length) + process.nextTick(run); + tests.push(fn); +} + +function run() { + var fn = tests.shift(); + if (fn) { + console.log('# %s', fn.name); + fn(run); + } else + console.log('ok'); +} + +test(function serverTimeout(cb) { + var caughtTimeout = false; + process.on('exit', function() { + assert(caughtTimeout); + }); + var server = https.createServer(serverOptions, function(req, res) { + // just do nothing, we should get a timeout event. + }); + server.listen(common.PORT); + server.setTimeout(50, function(socket) { + caughtTimeout = true; + socket.destroy(); + server.close(); + cb(); + }); + https.get({ + port: common.PORT, + rejectUnauthorized: false + }).on('error', function() {}); +}); + +test(function serverRequestTimeout(cb) { + var caughtTimeout = false; + process.on('exit', function() { + assert(caughtTimeout); + }); + var server = https.createServer(serverOptions, function(req, res) { + // just do nothing, we should get a timeout event. + req.setTimeout(50, function() { + caughtTimeout = true; + req.socket.destroy(); + server.close(); + cb(); + }); + }); + server.listen(common.PORT); + var req = https.request({ + port: common.PORT, + method: 'POST', + rejectUnauthorized: false + }); + req.on('error', function() {}); + req.write('Hello'); + // req is in progress +}); + +test(function serverResponseTimeout(cb) { + var caughtTimeout = false; + process.on('exit', function() { + assert(caughtTimeout); + }); + var server = https.createServer(serverOptions, function(req, res) { + // just do nothing, we should get a timeout event. + res.setTimeout(50, function() { + caughtTimeout = true; + res.socket.destroy(); + server.close(); + cb(); + }); + }); + server.listen(common.PORT); + https.get({ + port: common.PORT, + rejectUnauthorized: false + }).on('error', function() {}); +}); + +test(function serverRequestNotTimeoutAfterEnd(cb) { + var caughtTimeoutOnRequest = false; + var caughtTimeoutOnResponse = false; + process.on('exit', function() { + assert(!caughtTimeoutOnRequest); + assert(caughtTimeoutOnResponse); + }); + var server = https.createServer(serverOptions, function(req, res) { + // just do nothing, we should get a timeout event. + req.setTimeout(50, function(socket) { + caughtTimeoutOnRequest = true; + }); + res.on('timeout', function(socket) { + caughtTimeoutOnResponse = true; + }); + }); + server.on('timeout', function(socket) { + socket.destroy(); + server.close(); + cb(); + }); + server.listen(common.PORT); + https.get({ + port: common.PORT, + rejectUnauthorized: false + }).on('error', function() {}); +}); + +test(function serverResponseTimeoutWithPipeline(cb) { + var caughtTimeout = ''; + process.on('exit', function() { + assert.equal(caughtTimeout, '/2'); + }); + var server = https.createServer(serverOptions, function(req, res) { + res.setTimeout(50, function() { + caughtTimeout += req.url; + }); + if (req.url === '/1') res.end(); + }); + server.on('timeout', function(socket) { + socket.destroy(); + server.close(); + cb(); + }); + server.listen(common.PORT); + var options = { + port: common.PORT, + allowHalfOpen: true, + rejectUnauthorized: false + }; + var c = tls.connect(options, function() { + c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + }); +}); + +test(function idleTimeout(cb) { + var caughtTimeoutOnRequest = false; + var caughtTimeoutOnResponse = false; + var caughtTimeoutOnServer = false; + process.on('exit', function() { + assert(!caughtTimeoutOnRequest); + assert(!caughtTimeoutOnResponse); + assert(caughtTimeoutOnServer); + }); + var server = https.createServer(serverOptions, function(req, res) { + req.on('timeout', function(socket) { + caughtTimeoutOnRequest = true; + }); + res.on('timeout', function(socket) { + caughtTimeoutOnResponse = true; + }); + res.end(); + }); + server.setTimeout(50, function(socket) { + caughtTimeoutOnServer = true; + socket.destroy(); + server.close(); + cb(); + }); + server.listen(common.PORT); + var options = { + port: common.PORT, + allowHalfOpen: true, + rejectUnauthorized: false + }; + tls.connect(options, function() { + this.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); + // Keep-Alive + }); +}); diff --git a/test/parallel/test-https-simple.js b/test/parallel/test-https-simple.js new file mode 100644 index 000000000..552450c30 --- /dev/null +++ b/test/parallel/test-https-simple.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var exec = require('child_process').exec; + +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var reqCount = 0; +var body = 'hello world\n'; + +var server = https.createServer(options, function(req, res) { + reqCount++; + console.log('got request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server.listen(common.PORT, function() { + var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/'; + console.error('executing %j', cmd); + exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + common.error(common.inspect(stdout)); + assert.equal(body, stdout); + + // Do the same thing now without --insecure + // The connection should not be accepted. + var cmd = 'curl https://127.0.0.1:' + common.PORT + '/'; + console.error('executing %j', cmd); + exec(cmd, function(err, stdout, stderr) { + assert.ok(err); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(1, reqCount); +}); diff --git a/test/parallel/test-https-socket-options.js b/test/parallel/test-https-socket-options.js new file mode 100644 index 000000000..21b1118f7 --- /dev/null +++ b/test/parallel/test-https-socket-options.js @@ -0,0 +1,88 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var exec = require('child_process').exec; + +var http = require('http'); +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var body = 'hello world\n'; + +// Try first with http server + +var server_http = http.createServer(function(req, res) { + console.log('got HTTP request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + + +server_http.listen(common.PORT, function() { + var req = http.request({ + port: common.PORT, + rejectUnauthorized: false + }, function(res) { + server_http.close(); + res.resume(); + }); + // These methods should exist on the request and get passed down to the socket + req.setNoDelay(true); + req.setTimeout(1000, function() { }); + req.setSocketKeepAlive(true, 1000); + req.end(); +}); + +// Then try https server (requires functions to be mirroed in tls.js's CryptoStream) + +var server_https = https.createServer(options, function(req, res) { + console.log('got HTTPS request'); + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end(body); +}); + +server_https.listen(common.PORT+1, function() { + var req = https.request({ + port: common.PORT + 1, + rejectUnauthorized: false + }, function(res) { + server_https.close(); + res.resume(); + }); + // These methods should exist on the request and get passed down to the socket + req.setNoDelay(true); + req.setTimeout(1000, function() { }); + req.setSocketKeepAlive(true, 1000); + req.end(); +}); diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js new file mode 100644 index 000000000..9cd763f7a --- /dev/null +++ b/test/parallel/test-https-strict.js @@ -0,0 +1,226 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +// disable strict server certificate validation by the client +process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var path = require('path'); +var https = require('https'); + +function file(fname) { + return path.resolve(common.fixturesDir, 'keys', fname); +} + +function read(fname) { + return fs.readFileSync(file(fname)); +} + +// key1 is signed by ca1. +var key1 = read('agent1-key.pem'); +var cert1 = read('agent1-cert.pem'); + +// key2 has a self signed cert +var key2 = read('agent2-key.pem'); +var cert2 = read('agent2-cert.pem'); + +// key3 is signed by ca2. +var key3 = read('agent3-key.pem'); +var cert3 = read('agent3-cert.pem'); + +var ca1 = read('ca1-cert.pem'); +var ca2 = read('ca2-cert.pem'); + +// different agents to use different CA lists. +// this api is beyond bad. +var agent0 = new https.Agent(); +var agent1 = new https.Agent({ ca: [ca1] }); +var agent2 = new https.Agent({ ca: [ca2] }); +var agent3 = new https.Agent({ ca: [ca1, ca2] }); + +var options1 = { + key: key1, + cert: cert1 +}; + +var options2 = { + key: key2, + cert: cert2 +}; + +var options3 = { + key: key3, + cert: cert3 +}; + +var server1 = server(options1); +var server2 = server(options2); +var server3 = server(options3); + +var listenWait = 0; + +var port = common.PORT; +var port1 = port++; +var port2 = port++; +var port3 = port++; +server1.listen(port1, listening()); +server2.listen(port2, listening()); +server3.listen(port3, listening()); + +var responseErrors = {}; +var expectResponseCount = 0; +var responseCount = 0; +var pending = 0; + + + +function server(options, port) { + var s = https.createServer(options, handler); + s.requests = []; + s.expectCount = 0; + return s; +} + +function handler(req, res) { + this.requests.push(req.url); + res.statusCode = 200; + res.setHeader('foo', 'bar'); + res.end('hello, world\n'); +} + +function listening() { + listenWait++; + return function() { + listenWait--; + if (listenWait === 0) { + allListening(); + } + } +} + +function makeReq(path, port, error, host, ca) { + pending++; + var options = { + port: port, + path: path, + ca: ca + }; + var whichCa = 0; + if (!ca) { + options.agent = agent0; + } else { + if (!Array.isArray(ca)) ca = [ca]; + if (-1 !== ca.indexOf(ca1) && -1 !== ca.indexOf(ca2)) { + options.agent = agent3; + } else if (-1 !== ca.indexOf(ca1)) { + options.agent = agent1; + } else if (-1 !== ca.indexOf(ca2)) { + options.agent = agent2; + } else { + options.agent = agent0; + } + } + + if (host) { + options.headers = { host: host } + } + var req = https.get(options); + expectResponseCount++; + var server = port === port1 ? server1 + : port === port2 ? server2 + : port === port3 ? server3 + : null; + + if (!server) throw new Error('invalid port: '+port); + server.expectCount++; + + req.on('response', function(res) { + responseCount++; + assert.equal(res.connection.authorizationError, error); + responseErrors[path] = res.connection.authorizationError; + pending--; + if (pending === 0) { + server1.close(); + server2.close(); + server3.close(); + } + res.resume(); + }) +} + +function allListening() { + // ok, ready to start the tests! + + // server1: host 'agent1', signed by ca1 + makeReq('/inv1', port1, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); + makeReq('/inv1-ca1', port1, + 'Hostname/IP doesn\'t match certificate\'s altnames: ' + + '"Host: localhost. is not cert\'s CN: agent1"', + null, ca1); + makeReq('/inv1-ca1ca2', port1, + 'Hostname/IP doesn\'t match certificate\'s altnames: ' + + '"Host: localhost. is not cert\'s CN: agent1"', + null, [ca1, ca2]); + makeReq('/val1-ca1', port1, null, 'agent1', ca1); + makeReq('/val1-ca1ca2', port1, null, 'agent1', [ca1, ca2]); + makeReq('/inv1-ca2', port1, + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca2); + + // server2: self-signed, host = 'agent2' + // doesn't matter that thename matches, all of these will error. + makeReq('/inv2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT'); + makeReq('/inv2-ca1', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'agent2', ca1); + makeReq('/inv2-ca1ca2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'agent2', [ca1, ca2]); + + // server3: host 'agent3', signed by ca2 + makeReq('/inv3', port3, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); + makeReq('/inv3-ca2', port3, + 'Hostname/IP doesn\'t match certificate\'s altnames: ' + + '"Host: localhost. is not cert\'s CN: agent3"', + null, ca2); + makeReq('/inv3-ca1ca2', port3, + 'Hostname/IP doesn\'t match certificate\'s altnames: ' + + '"Host: localhost. is not cert\'s CN: agent3"', + null, [ca1, ca2]); + makeReq('/val3-ca2', port3, null, 'agent3', ca2); + makeReq('/val3-ca1ca2', port3, null, 'agent3', [ca1, ca2]); + makeReq('/inv3-ca1', port3, + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca1); + +} + +process.on('exit', function() { + console.error(responseErrors); + assert.equal(server1.requests.length, server1.expectCount); + assert.equal(server2.requests.length, server2.expectCount); + assert.equal(server3.requests.length, server3.expectCount); + assert.equal(responseCount, expectResponseCount); +}); diff --git a/test/parallel/test-https-timeout-server-2.js b/test/parallel/test-https-timeout-server-2.js new file mode 100644 index 000000000..076a0ec26 --- /dev/null +++ b/test/parallel/test-https-timeout-server-2.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) process.exit(); + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var net = require('net'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = https.createServer(options, assert.fail); + +server.on('secureConnection', function(cleartext) { + cleartext.setTimeout(50, function() { + cleartext.destroy(); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + tls.connect({ + host: '127.0.0.1', + port: common.PORT, + rejectUnauthorized: false + }); +}); diff --git a/test/parallel/test-https-timeout-server.js b/test/parallel/test-https-timeout-server.js new file mode 100644 index 000000000..57d6c57b5 --- /dev/null +++ b/test/parallel/test-https-timeout-server.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) process.exit(); + +var common = require('../common'); +var assert = require('assert'); +var https = require('https'); +var net = require('net'); +var tls = require('tls'); +var fs = require('fs'); + +var clientErrors = 0; + +process.on('exit', function() { + assert.equal(clientErrors, 1); +}); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), + handshakeTimeout: 50 +}; + +var server = https.createServer(options, assert.fail); + +server.on('clientError', function(err, conn) { + // Don't hesitate to update the asserts if the internal structure of + // the cleartext object ever changes. We're checking that the https.Server + // has closed the client connection. + assert.equal(conn._secureEstablished, false); + server.close(); + clientErrors++; +}); + +server.listen(common.PORT, function() { + net.connect({ host: '127.0.0.1', port: common.PORT }); +}); diff --git a/test/parallel/test-https-timeout.js b/test/parallel/test-https-timeout.js new file mode 100644 index 000000000..8b79204d4 --- /dev/null +++ b/test/parallel/test-https-timeout.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var exec = require('child_process').exec; +var https = require('https'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +// a server that never replies +var server = https.createServer(options, function() { + console.log('Got request. Doing nothing.'); +}).listen(common.PORT, function() { + var req = https.request({ + host: 'localhost', + port: common.PORT, + path: '/', + method: 'GET', + rejectUnauthorized: false + }); + req.setTimeout(10); + req.end(); + + req.on('response', function(res) { + console.log('got response'); + }); + + req.on('socket', function() { + console.log('got a socket'); + + req.socket.on('connect', function() { + console.log('socket connected'); + }); + + setTimeout(function() { + throw new Error('Did not get timeout event'); + }, 200); + }); + + req.on('timeout', function() { + console.log('timeout occurred outside'); + req.destroy(); + server.close(); + process.exit(0); + }); +}); diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js new file mode 100644 index 000000000..889f91682 --- /dev/null +++ b/test/parallel/test-https-truncate.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var https = require('https'); +var path = require('path'); + +var resultFile = path.resolve(common.tmpDir, 'result'); + +var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); +var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); + +var PORT = common.PORT; + +// number of bytes discovered empirically to trigger the bug +var data = new Buffer(1024 * 32 + 1); + +httpsTest(); + +function httpsTest() { + var sopt = { key: key, cert: cert }; + + var server = https.createServer(sopt, function(req, res) { + res.setHeader('content-length', data.length); + res.end(data); + server.close(); + }); + + server.listen(PORT, function() { + var opts = { port: PORT, rejectUnauthorized: false }; + https.get(opts).on('response', function(res) { + test(res); + }); + }); +} + + +function test(res) { + res.on('end', function() { + assert.equal(res._readableState.length, 0); + assert.equal(bytes, data.length); + console.log('ok'); + }); + + // Pause and then resume on each chunk, to ensure that there will be + // a lone byte hanging out at the very end. + var bytes = 0; + res.on('data', function(chunk) { + bytes += chunk.length; + this.pause(); + setTimeout(this.resume.bind(this)); + }); +} diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js new file mode 100644 index 000000000..0d6d7748a --- /dev/null +++ b/test/parallel/test-listen-fd-cluster.js @@ -0,0 +1,136 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; +var cluster = require('cluster'); + +console.error('Cluster listen fd test', process.argv.slice(2)); + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'master': return master(); + case 'worker': return worker(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the cluster. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var cluster = JSON.parse(json); + // now make sure that we can request to the worker, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the worker before we start doing asserts. + // it's really annoying when tests leave orphans! + parent.kill(); + process.kill(cluster.master, 'SIGKILL'); + + assert.equal(s, 'hello from worker\n'); + assert.equal(res.statusCode, 200); + console.log('ok'); + }); + }) + } +} + +function parent() { + console.error('about to listen in parent'); + var server = net.createServer(function(conn) { + console.error('connection on parent'); + conn.end('hello from parent\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var spawn = require('child_process').spawn; + var master = spawn(process.execPath, [__filename, 'master'], { + stdio: [ 0, 1, 2, server._handle ], + detached: true + }); + + // Now close the parent, so that the master is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the master has the fd open. + server.close(); + + master.on('exit', function(code) { + console.error('master exited', code); + }); + + master.on('close', function() { + console.error('master closed'); + }); + console.error('master spawned'); + }); +} + +function master() { + console.error('in master, spawning worker'); + cluster.setupMaster({ + args: [ 'worker' ] + }); + var worker = cluster.fork(); + console.log('%j\n', { master: process.pid, worker: worker.pid }); +} + + +function worker() { + console.error('worker, about to create server and listen on fd=3'); + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on worker'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from worker\n'); + }).listen({ fd: 3 }, function() { + console.error('worker listening on fd=3'); + }); +} diff --git a/test/parallel/test-listen-fd-detached-inherit.js b/test/parallel/test-listen-fd-detached-inherit.js new file mode 100644 index 000000000..dabc46cd3 --- /dev/null +++ b/test/parallel/test-listen-fd-detached-inherit.js @@ -0,0 +1,119 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'child': return child(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the child. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var child = JSON.parse(json); + // now make sure that we can request to the child, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the child before we start doing asserts. + // it's really annoying when tests leave orphans! + process.kill(child.pid, 'SIGKILL'); + try { + parent.kill(); + } catch (e) {} + + assert.equal(s, 'hello from child\n'); + assert.equal(res.statusCode, 200); + }); + }) + } +} + +// Listen on PORT, and then pass the handle to the detached child. +// Then output the child's pid, and immediately exit. +function parent() { + var server = net.createServer(function(conn) { + throw new Error('Should not see connections on parent'); + conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: [ 0, 1, 2, server._handle ], + detached: true + }); + + console.log('%j\n', { pid: child.pid }); + + // Now close the parent, so that the child is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the child has the fd open, but the parent + // will exit gracefully. + server.close(); + child.unref(); + }); +} + +// Run as a child of the parent() mode. +function child() { + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on child'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from child\n'); + }).listen({ fd: 3 }, function() { + console.error('child listening on fd=3'); + }); +} + diff --git a/test/parallel/test-listen-fd-detached.js b/test/parallel/test-listen-fd-detached.js new file mode 100644 index 000000000..3d98abeac --- /dev/null +++ b/test/parallel/test-listen-fd-detached.js @@ -0,0 +1,117 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'child': return child(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the child. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var child = JSON.parse(json); + // now make sure that we can request to the child, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the child before we start doing asserts. + // it's really annoying when tests leave orphans! + process.kill(child.pid, 'SIGKILL'); + try { + parent.kill(); + } catch (e) {} + + assert.equal(s, 'hello from child\n'); + assert.equal(res.statusCode, 200); + }); + }) + } +} + +function parent() { + var server = net.createServer(function(conn) { + console.error('connection on parent'); + conn.end('hello from parent\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], + detached: true + }); + + console.log('%j\n', { pid: child.pid }); + + // Now close the parent, so that the child is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the child has the fd open, but the parent + // will exit gracefully. + server.close(); + child.unref(); + }); +} + +function child() { + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on child'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from child\n'); + }).listen({ fd: 3 }, function() { + console.error('child listening on fd=3'); + }); +} + diff --git a/test/parallel/test-listen-fd-ebadf.js b/test/parallel/test-listen-fd-ebadf.js new file mode 100644 index 000000000..6c0f20ae4 --- /dev/null +++ b/test/parallel/test-listen-fd-ebadf.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = 0; + +process.on('exit', function() { + assert.equal(gotError, 2); +}); + +net.createServer(assert.fail).listen({fd:2}).on('error', onError); +net.createServer(assert.fail).listen({fd:42}).on('error', onError); + +function onError(ex) { + assert.equal(ex.code, 'EINVAL'); + gotError++; +} diff --git a/test/parallel/test-listen-fd-server.js b/test/parallel/test-listen-fd-server.js new file mode 100644 index 000000000..8f3454fbb --- /dev/null +++ b/test/parallel/test-listen-fd-server.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); +var PORT = common.PORT; +var spawn = require('child_process').spawn; + +if (process.platform === 'win32') { + console.error('This test is disabled on windows.'); + return; +} + +switch (process.argv[2]) { + case 'child': return child(); + case 'parent': return parent(); + default: return test(); +} + +// spawn the parent, and listen for it to tell us the pid of the child. +// WARNING: This is an example of listening on some arbitrary FD number +// that has already been bound elsewhere in advance. However, binding +// server handles to stdio fd's is NOT a good or reliable way to do +// concurrency in HTTP servers! Use the cluster module, or if you want +// a more low-level approach, use child process IPC manually. +function test() { + var parent = spawn(process.execPath, [__filename, 'parent'], { + stdio: [ 0, 'pipe', 2 ] + }); + var json = ''; + parent.stdout.on('data', function(c) { + json += c.toString(); + if (json.indexOf('\n') !== -1) next(); + }); + function next() { + console.error('output from parent = %s', json); + var child = JSON.parse(json); + // now make sure that we can request to the child, then kill it. + http.get({ + server: 'localhost', + port: PORT, + path: '/', + }).on('response', function (res) { + var s = ''; + res.on('data', function(c) { + s += c.toString(); + }); + res.on('end', function() { + // kill the child before we start doing asserts. + // it's really annoying when tests leave orphans! + process.kill(child.pid, 'SIGKILL'); + try { + parent.kill(); + } catch (e) {} + + assert.equal(s, 'hello from child\n'); + assert.equal(res.statusCode, 200); + }); + }) + } +} + +function child() { + // start a server on fd=3 + http.createServer(function(req, res) { + console.error('request on child'); + console.error('%s %s', req.method, req.url, req.headers); + res.end('hello from child\n'); + }).listen({ fd: 3 }, function() { + console.error('child listening on fd=3'); + }); +} + +function parent() { + var server = net.createServer(function(conn) { + console.error('connection on parent'); + conn.end('hello from parent\n'); + }).listen(PORT, function() { + console.error('server listening on %d', PORT); + + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: [ 0, 1, 2, server._handle ] + }); + + console.log('%j\n', { pid: child.pid }); + + // Now close the parent, so that the child is the only thing + // referencing that handle. Note that connections will still + // be accepted, because the child has the fd open. + server.close(); + + child.on('exit', function(code) { + console.error('child exited', code); + }); + + child.on('close', function() { + console.error('child closed'); + }); + console.error('child spawned'); + }); +} diff --git a/test/parallel/test-memory-usage.js b/test/parallel/test-memory-usage.js new file mode 100644 index 000000000..0df17420c --- /dev/null +++ b/test/parallel/test-memory-usage.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var r = process.memoryUsage(); +console.log(common.inspect(r)); +assert.equal(true, r['rss'] > 0); diff --git a/test/parallel/test-microtask-queue-integration-domain.js b/test/parallel/test-microtask-queue-integration-domain.js new file mode 100644 index 000000000..2197bf921 --- /dev/null +++ b/test/parallel/test-microtask-queue-integration-domain.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); + +var implementations = [ + function (fn) { + Promise.resolve().then(fn); + }, + function (fn) { + var obj = {}; + + Object.observe(obj, fn); + + obj.a = 1; + } +]; + +var expected = 0; +var done = 0; + +process.on('exit', function () { + assert.equal(done, expected); +}); + +function test (scheduleMicrotask) { + var nextTickCalled = false; + expected++; + + scheduleMicrotask(function () { + process.nextTick(function () { + nextTickCalled = true; + }); + + setTimeout(function () { + assert(nextTickCalled); + done++; + }, 0); + }); +} + +// first tick case +implementations.forEach(test); + +// tick callback case +setTimeout(function () { + implementations.forEach(function (impl) { + process.nextTick(test.bind(null, impl)); + }); +}, 0); diff --git a/test/parallel/test-microtask-queue-integration.js b/test/parallel/test-microtask-queue-integration.js new file mode 100644 index 000000000..af0154847 --- /dev/null +++ b/test/parallel/test-microtask-queue-integration.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var implementations = [ + function (fn) { + Promise.resolve().then(fn); + }, + function (fn) { + var obj = {}; + + Object.observe(obj, fn); + + obj.a = 1; + } +]; + +var expected = 0; +var done = 0; + +process.on('exit', function () { + assert.equal(done, expected); +}); + +function test (scheduleMicrotask) { + var nextTickCalled = false; + expected++; + + scheduleMicrotask(function () { + process.nextTick(function () { + nextTickCalled = true; + }); + + setTimeout(function () { + assert(nextTickCalled); + done++; + }, 0); + }); +} + +// first tick case +implementations.forEach(test); + +// tick callback case +setTimeout(function () { + implementations.forEach(function (impl) { + process.nextTick(test.bind(null, impl)); + }); +}, 0); diff --git a/test/parallel/test-microtask-queue-run-domain.js b/test/parallel/test-microtask-queue-run-domain.js new file mode 100644 index 000000000..2b3b76315 --- /dev/null +++ b/test/parallel/test-microtask-queue-run-domain.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); + +function enqueueMicrotask(fn) { + Promise.resolve().then(fn); +} + +var done = 0; + +process.on('exit', function() { + assert.equal(done, 2); +}); + +// no nextTick, microtask +setTimeout(function() { + enqueueMicrotask(function() { + done++; + }); +}, 0); + + +// no nextTick, microtask with nextTick +setTimeout(function() { + var called = false; + + enqueueMicrotask(function() { + process.nextTick(function() { + called = true; + }); + }); + + setTimeout(function() { + if (called) + done++; + }, 0); + +}, 0); diff --git a/test/parallel/test-microtask-queue-run-immediate-domain.js b/test/parallel/test-microtask-queue-run-immediate-domain.js new file mode 100644 index 000000000..8f95fadd5 --- /dev/null +++ b/test/parallel/test-microtask-queue-run-immediate-domain.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var domain = require('domain'); + +function enqueueMicrotask(fn) { + Promise.resolve().then(fn); +} + +var done = 0; + +process.on('exit', function() { + assert.equal(done, 2); +}); + +// no nextTick, microtask +setImmediate(function() { + enqueueMicrotask(function() { + done++; + }); +}); + + +// no nextTick, microtask with nextTick +setImmediate(function() { + var called = false; + + enqueueMicrotask(function() { + process.nextTick(function() { + called = true; + }); + }); + + setImmediate(function() { + if (called) + done++; + }); + +}); diff --git a/test/parallel/test-microtask-queue-run-immediate.js b/test/parallel/test-microtask-queue-run-immediate.js new file mode 100644 index 000000000..b5423eb6b --- /dev/null +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +function enqueueMicrotask(fn) { + Promise.resolve().then(fn); +} + +var done = 0; + +process.on('exit', function() { + assert.equal(done, 2); +}); + +// no nextTick, microtask +setImmediate(function() { + enqueueMicrotask(function() { + done++; + }); +}); + + +// no nextTick, microtask with nextTick +setImmediate(function() { + var called = false; + + enqueueMicrotask(function() { + process.nextTick(function() { + called = true; + }); + }); + + setImmediate(function() { + if (called) + done++; + }); + +}); diff --git a/test/parallel/test-microtask-queue-run.js b/test/parallel/test-microtask-queue-run.js new file mode 100644 index 000000000..c4138454f --- /dev/null +++ b/test/parallel/test-microtask-queue-run.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +function enqueueMicrotask(fn) { + Promise.resolve().then(fn); +} + +var done = 0; + +process.on('exit', function() { + assert.equal(done, 2); +}); + +// no nextTick, microtask +setTimeout(function() { + enqueueMicrotask(function() { + done++; + }); +}, 0); + + +// no nextTick, microtask with nextTick +setTimeout(function() { + var called = false; + + enqueueMicrotask(function() { + process.nextTick(function() { + called = true; + }); + }); + + setTimeout(function() { + if (called) + done++; + }, 0); + +}, 0); diff --git a/test/parallel/test-module-globalpaths-nodepath.js b/test/parallel/test-module-globalpaths-nodepath.js new file mode 100644 index 000000000..c99b6763b --- /dev/null +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var module = require('module'); + +var isWindows = process.platform === 'win32'; + +var partA, partB; + +if (isWindows) { + partA = 'C:\\Users\\Rocko Artischocko\\AppData\\Roaming\\npm'; + partB = 'C:\\Program Files (x86)\\nodejs\\'; + process.env['NODE_PATH'] = partA + ';' + partB; +} else { + partA = '/usr/test/lib/node_modules'; + partB = '/usr/test/lib/node'; + process.env['NODE_PATH'] = partA + ':' + partB; +} + +module._initPaths(); + +assert.ok(module.globalPaths.indexOf(partA) !== -1); +assert.ok(module.globalPaths.indexOf(partB) !== -1); + +assert.ok(Array.isArray(module.globalPaths)); \ No newline at end of file diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js new file mode 100644 index 000000000..beddb5d37 --- /dev/null +++ b/test/parallel/test-module-loading-error.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.debug('load test-module-loading-error.js'); + +var error_desc = { + win32: '%1 is not a valid Win32 application', + linux: 'file too short', + sunos: 'unknown file type' +}; + +var dlerror_msg = error_desc[process.platform]; + +if (!dlerror_msg) { + console.error('Skipping test, platform not supported.'); + process.exit(); +} + +try { + require('../fixtures/module-loading-error.node'); +} catch (e) { + assert.notEqual(e.toString().indexOf(dlerror_msg), -1); +} + +try { + require(); +} catch (e) { + assert.notEqual(e.toString().indexOf('missing path'), -1); +} + +try { + require({}); +} catch (e) { + assert.notEqual(e.toString().indexOf('path must be a string'), -1); +} diff --git a/test/parallel/test-module-nodemodulepaths.js b/test/parallel/test-module-nodemodulepaths.js new file mode 100644 index 000000000..3d48d99ab --- /dev/null +++ b/test/parallel/test-module-nodemodulepaths.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var module = require('module'); + +var isWindows = process.platform === 'win32'; + +var file, delimiter, paths; + +if (isWindows) { + file = 'C:\\Users\\Rocko Artischocko\\node_stuff\\foo'; + delimiter = '\\' +} else { + file = '/usr/test/lib/node_modules/npm/foo'; + delimiter = '/' +} + +paths = module._nodeModulePaths(file); + +assert.ok(paths.indexOf(file + delimiter + 'node_modules') !== -1); +assert.ok(Array.isArray(paths)); \ No newline at end of file diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js new file mode 100644 index 000000000..2f3d4c379 --- /dev/null +++ b/test/parallel/test-net-after-close.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var closed = false; + +var server = net.createServer(function(s) { + console.error('SERVER: got connection'); + s.end(); +}); + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + c.on('close', function() { + console.error('connection closed'); + assert.strictEqual(c._handle, null); + closed = true; + assert.doesNotThrow(function() { + c.setNoDelay(); + c.setKeepAlive(); + c.bufferSize; + c.pause(); + c.resume(); + c.address(); + c.remoteAddress; + c.remotePort; + }); + server.close(); + }); +}); + +process.on('exit', function() { + assert(closed); +}); diff --git a/test/parallel/test-net-better-error-messages-listen-path.js b/test/parallel/test-net-better-error-messages-listen-path.js new file mode 100644 index 000000000..fcc3062a8 --- /dev/null +++ b/test/parallel/test-net-better-error-messages-listen-path.js @@ -0,0 +1,9 @@ +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var fp = '/blah/fadfa'; +var server = net.createServer(assert.fail); +server.listen(fp, assert.fail); +server.on('error', common.mustCall(function(e) { + assert.equal(e.address, fp) +})); diff --git a/test/parallel/test-net-better-error-messages-listen.js b/test/parallel/test-net-better-error-messages-listen.js new file mode 100644 index 000000000..9c7766bd4 --- /dev/null +++ b/test/parallel/test-net-better-error-messages-listen.js @@ -0,0 +1,11 @@ +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var server = net.createServer(assert.fail); +server.listen(1, '1.1.1.1', assert.fail); +server.on('error', common.mustCall(function(e) { + assert.equal(e.address, '1.1.1.1'); + assert.equal(e.port, 1); + assert.equal(e.syscall, 'listen'); +})); diff --git a/test/parallel/test-net-better-error-messages-path.js b/test/parallel/test-net-better-error-messages-path.js new file mode 100644 index 000000000..dea4a1045 --- /dev/null +++ b/test/parallel/test-net-better-error-messages-path.js @@ -0,0 +1,12 @@ +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); +var fp = '/tmp/fadagagsdfgsdf'; +var c = net.connect(fp); + +c.on('connect', assert.fail); + +c.on('error', common.mustCall(function(e) { + assert.equal(e.code, 'ENOENT'); + assert.equal(e.message, 'connect ENOENT ' + fp); +})); diff --git a/test/parallel/test-net-better-error-messages-port-hostname.js b/test/parallel/test-net-better-error-messages-port-hostname.js new file mode 100644 index 000000000..3817dbb92 --- /dev/null +++ b/test/parallel/test-net-better-error-messages-port-hostname.js @@ -0,0 +1,13 @@ +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var c = net.createConnection(common.PORT, 'blah.blah'); + +c.on('connect', assert.fail); + +c.on('error', common.mustCall(function(e) { + assert.equal(e.code, 'ENOTFOUND'); + assert.equal(e.port, common.PORT); + assert.equal(e.hostname, 'blah.blah'); +})); diff --git a/test/parallel/test-net-better-error-messages-port.js b/test/parallel/test-net-better-error-messages-port.js new file mode 100644 index 000000000..a8c16a703 --- /dev/null +++ b/test/parallel/test-net-better-error-messages-port.js @@ -0,0 +1,13 @@ +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var c = net.createConnection(common.PORT); + +c.on('connect', assert.fail); + +c.on('error', common.mustCall(function(e) { + assert.equal(e.code, 'ECONNREFUSED'); + assert.equal(e.port, common.PORT); + assert.equal(e.address, '127.0.0.1'); +})); diff --git a/test/parallel/test-net-binary.js b/test/parallel/test-net-binary.js new file mode 100644 index 000000000..310046584 --- /dev/null +++ b/test/parallel/test-net-binary.js @@ -0,0 +1,112 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var binaryString = ''; +for (var i = 255; i >= 0; i--) { + var s = '\'\\' + i.toString(8) + '\''; + var S = eval(s); + common.error(s + + ' ' + + JSON.stringify(S) + + ' ' + + JSON.stringify(String.fromCharCode(i)) + + ' ' + + S.charCodeAt(0)); + assert.ok(S.charCodeAt(0) == i); + assert.ok(S == String.fromCharCode(i)); + binaryString += S; +} + +// safe constructor +var echoServer = net.Server(function(connection) { + console.error('SERVER got connection'); + connection.setEncoding('binary'); + connection.on('data', function(chunk) { + common.error('SERVER recved: ' + JSON.stringify(chunk)); + connection.write(chunk, 'binary'); + }); + connection.on('end', function() { + console.error('SERVER ending'); + connection.end(); + }); +}); +echoServer.listen(common.PORT); + +var recv = ''; + +echoServer.on('listening', function() { + console.error('SERVER listening'); + var j = 0; + var c = net.createConnection({ + port: common.PORT + }); + + c.setEncoding('binary'); + c.on('data', function(chunk) { + console.error('CLIENT data %j', chunk); + var n = j + chunk.length; + while (j < n && j < 256) { + common.error('CLIENT write ' + j); + c.write(String.fromCharCode(j), 'binary'); + j++; + } + if (j === 256) { + console.error('CLIENT ending'); + c.end(); + } + recv += chunk; + }); + + c.on('connect', function() { + console.error('CLIENT connected, writing'); + c.write(binaryString, 'binary'); + }); + + c.on('close', function() { + console.error('CLIENT closed'); + console.dir(recv); + echoServer.close(); + }); + + c.on('finish', function() { + console.error('CLIENT finished'); + }); +}); + +process.on('exit', function() { + console.log('recv: ' + JSON.stringify(recv)); + + assert.equal(2 * 256, recv.length); + + var a = recv.split(''); + + var first = a.slice(0, 256).reverse().join(''); + console.log('first: ' + JSON.stringify(first)); + + var second = a.slice(256, 2 * 256).join(''); + console.log('second: ' + JSON.stringify(second)); + + assert.equal(first, second); +}); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js new file mode 100644 index 000000000..58086cc96 --- /dev/null +++ b/test/parallel/test-net-bind-twice.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; + +process.on('exit', function() { + assert(gotError); +}); + +function dontCall() { + assert(false); +} + +var server1 = net.createServer(dontCall); +server1.listen(common.PORT, '127.0.0.1', function() {}); + +var server2 = net.createServer(dontCall); +server2.listen(common.PORT, '127.0.0.1', dontCall); + +server2.on('error', function(e) { + assert.equal(e.code, 'EADDRINUSE'); + server1.close(); + gotError = true; +}); diff --git a/test/parallel/test-net-buffersize.js b/test/parallel/test-net-buffersize.js new file mode 100644 index 000000000..5759503a1 --- /dev/null +++ b/test/parallel/test-net-buffersize.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var iter = 10; + +var server = net.createServer(function(socket) { + socket.on('readable', function() { + socket.read(); + }); + + socket.on('end', function() { + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var client = net.connect(common.PORT); + + client.on('finish', function() { + assert.strictEqual(client.bufferSize, 0); + }); + + for (var i = 1; i < iter; i++) { + client.write('a'); + assert.strictEqual(client.bufferSize, i); + } + + client.end(); +}); diff --git a/test/parallel/test-net-bytes-stats.js b/test/parallel/test-net-bytes-stats.js new file mode 100644 index 000000000..0cb08009e --- /dev/null +++ b/test/parallel/test-net-bytes-stats.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tcpPort = common.PORT; +var bytesRead = 0; +var bytesWritten = 0; +var count = 0; + +var tcp = net.Server(function(s) { + console.log('tcp server connection'); + + // trigger old mode. + s.resume(); + + s.on('end', function() { + bytesRead += s.bytesRead; + console.log('tcp socket disconnect #' + count); + }); +}); + +tcp.listen(common.PORT, function doTest() { + console.error('listening'); + var socket = net.createConnection(tcpPort); + + socket.on('connect', function() { + count++; + console.error('CLIENT connect #%d', count); + + socket.write('foo', function() { + console.error('CLIENT: write cb'); + socket.end('bar'); + }); + }); + + socket.on('finish', function() { + bytesWritten += socket.bytesWritten; + console.error('CLIENT end event #%d', count); + }); + + socket.on('close', function() { + console.error('CLIENT close event #%d', count); + console.log('Bytes read: ' + bytesRead); + console.log('Bytes written: ' + bytesWritten); + if (count < 2) { + console.error('RECONNECTING'); + socket.connect(tcpPort); + } else { + tcp.close(); + } + }); +}); + +process.on('exit', function() { + assert.equal(bytesRead, 12); + assert.equal(bytesWritten, 12); +}); diff --git a/test/parallel/test-net-can-reset-timeout.js b/test/parallel/test-net-can-reset-timeout.js new file mode 100644 index 000000000..b9ea97efe --- /dev/null +++ b/test/parallel/test-net-can-reset-timeout.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var net = require('net'); +var common = require('../common'); +var assert = require('assert'); + +var timeoutCount = 0; + +var server = net.createServer(function(stream) { + stream.setTimeout(100); + + stream.resume(); + + stream.on('timeout', function() { + console.log('timeout'); + // try to reset the timeout. + stream.write('WHAT.'); + // don't worry, the socket didn't *really* time out, we're just thinking + // it did. + timeoutCount += 1; + }); + + stream.on('end', function() { + console.log('server side end'); + stream.end(); + }); +}); + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('data', function() { + c.end(); + }); + + c.on('end', function() { + console.log('client side end'); + server.close(); + }); +}); + + +process.on('exit', function() { + assert.equal(1, timeoutCount); +}); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js new file mode 100644 index 000000000..679e18e90 --- /dev/null +++ b/test/parallel/test-net-connect-buffer.js @@ -0,0 +1,117 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tcpPort = common.PORT; +var dataWritten = false; +var connectHappened = false; + +var tcp = net.Server(function(s) { + tcp.close(); + + console.log('tcp server connection'); + + var buf = ''; + s.on('data', function(d) { + buf += d; + }); + + s.on('end', function() { + console.error('SERVER: end', buf.toString()); + assert.equal(buf, "L'État, c'est moi"); + console.log('tcp socket disconnect'); + s.end(); + }); + + s.on('error', function(e) { + console.log('tcp server-side error: ' + e.message); + process.exit(1); + }); +}); + +tcp.listen(common.PORT, function() { + var socket = net.Stream({ highWaterMark: 0 }); + + console.log('Connecting to socket '); + + socket.connect(tcpPort, function() { + console.log('socket connected'); + connectHappened = true; + }); + + console.log('_connecting = ' + socket._connecting); + + assert.equal('opening', socket.readyState); + + // Make sure that anything besides a buffer or a string throws. + [null, + true, + false, + undefined, + 1, + 1.0, + 1 / 0, + +Infinity, + -Infinity, + [], + {} + ].forEach(function(v) { + function f() { + console.error('write', v); + socket.write(v); + } + assert.throws(f, TypeError); + }); + + // Write a string that contains a multi-byte character sequence to test that + // `bytesWritten` is incremented with the # of bytes, not # of characters. + var a = "L'État, c'est "; + var b = 'moi'; + + // We're still connecting at this point so the datagram is first pushed onto + // the connect queue. Make sure that it's not added to `bytesWritten` again + // when the actual write happens. + var r = socket.write(a, function(er) { + console.error('write cb'); + dataWritten = true; + assert.ok(connectHappened); + console.error('socket.bytesWritten', socket.bytesWritten); + //assert.equal(socket.bytesWritten, Buffer(a + b).length); + console.error('data written'); + }); + console.error('socket.bytesWritten', socket.bytesWritten); + console.error('write returned', r); + + assert.equal(socket.bytesWritten, Buffer(a).length); + + assert.equal(false, r); + socket.end(b); + + assert.equal('opening', socket.readyState); +}); + +process.on('exit', function() { + assert.ok(connectHappened); + assert.ok(dataWritten); +}); diff --git a/test/parallel/test-net-connect-handle-econnrefused.js b/test/parallel/test-net-connect-handle-econnrefused.js new file mode 100644 index 000000000..e890b6a8d --- /dev/null +++ b/test/parallel/test-net-connect-handle-econnrefused.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + + +// Hopefully nothing is running on common.PORT +var c = net.createConnection(common.PORT); + +c.on('connect', function() { + console.error('connected?!'); + assert.ok(false); +}); + +var gotError = false; +c.on('error', function(e) { + console.error('couldn\'t connect.'); + gotError = true; + assert.equal('ECONNREFUSED', e.code); +}); + + +process.on('exit', function() { + assert.ok(gotError); +}); diff --git a/test/parallel/test-net-connect-immediate-finish.js b/test/parallel/test-net-connect-immediate-finish.js new file mode 100644 index 000000000..ac2a61331 --- /dev/null +++ b/test/parallel/test-net-connect-immediate-finish.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; + +var client = net.connect({ + host: 'no.way.you.will.resolve.this', + port: common.PORT +}); + +client.once('error', function(err) { + gotError = true; +}); + +client.end(); + +process.on('exit', function() { + assert(gotError); +}); diff --git a/test/parallel/test-net-connect-options-ipv6.js b/test/parallel/test-net-connect-options-ipv6.js new file mode 100644 index 000000000..9dd60c1cb --- /dev/null +++ b/test/parallel/test-net-connect-options-ipv6.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var dns = require('dns'); + +if (!common.hasIPv6) { + console.error('Skipping test, no IPv6 support'); + return; +} + +var serverGotEnd = false; +var clientGotEnd = false; + +dns.lookup('localhost', 6, function(err) { + if (err) { + console.error('Looks like IPv6 is not really supported'); + console.error(err); + return; + } + + var server = net.createServer({allowHalfOpen: true}, function(socket) { + socket.resume(); + socket.on('end', function() { + serverGotEnd = true; + }); + socket.end(); + }); + + server.listen(common.PORT, '::1', function() { + var client = net.connect({ + host: 'localhost', + port: common.PORT, + family: 6, + allowHalfOpen: true + }, function() { + console.error('client connect cb'); + client.resume(); + client.on('end', function() { + clientGotEnd = true; + setTimeout(function() { + assert(client.writable); + client.end(); + }, 10); + }); + client.on('close', function() { + server.close(); + }); + }); + }); + + process.on('exit', function() { + console.error('exit', serverGotEnd, clientGotEnd); + assert(serverGotEnd); + assert(clientGotEnd); + }); +}); diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js new file mode 100644 index 000000000..6be3696da --- /dev/null +++ b/test/parallel/test-net-connect-options.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var serverGotEnd = false; +var clientGotEnd = false; + +var server = net.createServer({allowHalfOpen: true}, function(socket) { + socket.resume(); + socket.on('end', function() { + serverGotEnd = true; + }); + socket.end(); +}); + +server.listen(common.PORT, function() { + var client = net.connect({ + host: '127.0.0.1', + port: common.PORT, + allowHalfOpen: true + }, function() { + console.error('client connect cb'); + client.resume(); + client.on('end', function() { + clientGotEnd = true; + setTimeout(function() { + assert(client.writable); + client.end(); + }, 10); + }); + client.on('close', function() { + server.close(); + }); + }); +}); + +process.on('exit', function() { + console.error('exit', serverGotEnd, clientGotEnd); + assert(serverGotEnd); + assert(clientGotEnd); +}); diff --git a/test/parallel/test-net-connect-paused-connection.js b/test/parallel/test-net-connect-paused-connection.js new file mode 100644 index 000000000..9d9db1040 --- /dev/null +++ b/test/parallel/test-net-connect-paused-connection.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. + +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: + +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); + +var net = require('net'); + +net.createServer(function(conn) { + conn.unref(); +}).listen(common.PORT).unref(); + +net.connect(common.PORT, 'localhost').pause(); + +setTimeout(function() { + assert.fail('expected to exit'); +}, 1000).unref(); diff --git a/test/parallel/test-net-create-connection.js b/test/parallel/test-net-create-connection.js new file mode 100644 index 000000000..12f7f0be6 --- /dev/null +++ b/test/parallel/test-net-create-connection.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var tcpPort = common.PORT; +var clientConnected = 0; +var serverConnected = 0; + +var server = net.createServer(function(socket) { + socket.end(); + if (++serverConnected === 4) { + server.close(); + } +}); +server.listen(tcpPort, 'localhost', function() { + function cb() { + ++clientConnected; + } + + net.createConnection(tcpPort).on('connect', cb); + net.createConnection(tcpPort, 'localhost').on('connect', cb); + net.createConnection(tcpPort, cb); + net.createConnection(tcpPort, 'localhost', cb); + + assert.throws(function () { + net.createConnection({ + port: 'invalid!' + }, cb); + }); +}); + +process.on('exit', function() { + assert.equal(clientConnected, 4); +}); + diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js new file mode 100644 index 000000000..f7221389a --- /dev/null +++ b/test/parallel/test-net-dns-error.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var expected_bad_connections = 1; +var actual_bad_connections = 0; + +var host = '********'; +host += host; +host += host; +host += host; +host += host; +host += host; + +function do_not_call() { + throw new Error('This function should not have been called.'); +} + +var socket = net.connect(42, host, do_not_call); +socket.on('error', function(err) { + assert.equal(err.code, 'ENOTFOUND'); + actual_bad_connections++; +}); +socket.on('lookup', function(err, ip, type) { + assert(err instanceof Error); + assert.equal(err.code, 'ENOTFOUND'); + assert.equal(ip, undefined); + assert.equal(type, undefined); +}); + +process.on('exit', function() { + assert.equal(actual_bad_connections, expected_bad_connections); +}); diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js new file mode 100644 index 000000000..5628e4d8a --- /dev/null +++ b/test/parallel/test-net-dns-lookup.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var ok = false; + +var server = net.createServer(function(client) { + client.end(); + server.close(); +}); + +server.listen(common.PORT, '127.0.0.1', function() { + net.connect(common.PORT, '127.0.0.1').on('lookup', function(err, ip, type) { + assert.equal(err, null); + assert.equal(ip, '127.0.0.1'); + assert.equal(type, '4'); + ok = true; + }); +}); + +process.on('exit', function() { + assert(ok); +}); diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js new file mode 100644 index 000000000..489d77479 --- /dev/null +++ b/test/parallel/test-net-during-close.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var accessedProperties = false; + +var server = net.createServer(function(socket) { + socket.end(); +}); + +server.listen(common.PORT, function() { + var client = net.createConnection(common.PORT); + server.close(); + // server connection event has not yet fired + // client is still attempting to connect + assert.doesNotThrow(function() { + client.remoteAddress; + client.remoteFamily; + client.remotePort; + }); + accessedProperties = true; + // exit now, do not wait for the client error event + process.exit(0); +}); + +process.on('exit', function() { + assert(accessedProperties); +}); diff --git a/test/parallel/test-net-eaddrinuse.js b/test/parallel/test-net-eaddrinuse.js new file mode 100644 index 000000000..2192ea224 --- /dev/null +++ b/test/parallel/test-net-eaddrinuse.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var server1 = net.createServer(function(socket) { +}); +var server2 = net.createServer(function(socket) { +}); +server1.listen(common.PORT); +server2.on('error', function(error) { + assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); + server1.close(); +}); +server2.listen(common.PORT); diff --git a/test/parallel/test-net-end-without-connect.js b/test/parallel/test-net-end-without-connect.js new file mode 100644 index 000000000..156071a0d --- /dev/null +++ b/test/parallel/test-net-end-without-connect.js @@ -0,0 +1,26 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); + +var sock = new net.Socket; +sock.end(); // Should not throw. diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js new file mode 100644 index 000000000..955eea6c0 --- /dev/null +++ b/test/parallel/test-net-error-twice.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var buf = new Buffer(10 * 1024 * 1024); + +buf.fill(0x62); + +var errs = []; + +var srv = net.createServer(function onConnection(conn) { + conn.write(buf); + conn.on('error', function (err) { + errs.push(err); + if (errs.length > 1 && errs[0] === errs[1]) + assert(false, "We should not be emitting the same error twice"); + }); + conn.on('close', function() { + srv.unref(); + }); +}).listen(common.PORT, function () { + var client = net.connect({ port: common.PORT }); + + client.on('connect', function () { + client.destroy(); + }); +}); + +process.on('exit', function() { + console.log(errs); + assert.equal(errs.length, 1); +}); diff --git a/test/parallel/test-net-isip.js b/test/parallel/test-net-isip.js new file mode 100644 index 000000000..0d324007f --- /dev/null +++ b/test/parallel/test-net-isip.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +assert.equal(net.isIP('127.0.0.1'), 4); +assert.equal(net.isIP('x127.0.0.1'), 0); +assert.equal(net.isIP('example.com'), 0); +assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6); +assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000::0000'), 0); +assert.equal(net.isIP('1050:0:0:0:5:600:300c:326b'), 6); +assert.equal(net.isIP('2001:252:0:1::2008:6'), 6); +assert.equal(net.isIP('2001:dead:beef:1::2008:6'), 6); +assert.equal(net.isIP('2001::'), 6); +assert.equal(net.isIP('2001:dead::'), 6); +assert.equal(net.isIP('2001:dead:beef::'), 6); +assert.equal(net.isIP('2001:dead:beef:1::'), 6); +assert.equal(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6); +assert.equal(net.isIP(':2001:252:0:1::2008:6:'), 0); +assert.equal(net.isIP(':2001:252:0:1::2008:6'), 0); +assert.equal(net.isIP('2001:252:0:1::2008:6:'), 0); +assert.equal(net.isIP('2001:252::1::2008:6'), 0); +assert.equal(net.isIP('::2001:252:1:2008:6'), 6); +assert.equal(net.isIP('::2001:252:1:1.1.1.1'), 6); +assert.equal(net.isIP('::2001:252:1:255.255.255.255'), 6); +assert.equal(net.isIP('::2001:252:1:255.255.255.255.76'), 0); +assert.equal(net.isIP('::anything'), 0); +assert.equal(net.isIP('::1'), 6); +assert.equal(net.isIP('::'), 6); +assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); +assert.equal(net.isIP('0'), 0); +assert.equal(net.isIP(), 0); +assert.equal(net.isIP(""), 0); + +assert.equal(net.isIPv4('127.0.0.1'), true); +assert.equal(net.isIPv4('example.com'), false); +assert.equal(net.isIPv4('2001:252:0:1::2008:6'), false); + +assert.equal(net.isIPv6('127.0.0.1'), false); +assert.equal(net.isIPv6('example.com'), false); +assert.equal(net.isIPv6('2001:252:0:1::2008:6'), true); diff --git a/test/parallel/test-net-keepalive.js b/test/parallel/test-net-keepalive.js new file mode 100644 index 000000000..b09d9d5d6 --- /dev/null +++ b/test/parallel/test-net-keepalive.js @@ -0,0 +1,51 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var serverConnection; +var echoServer = net.createServer(function(connection) { + serverConnection = connection; + connection.setTimeout(0); + assert.notEqual(connection.setKeepAlive, undefined); + // send a keepalive packet after 1000 ms + connection.setKeepAlive(true, 1000); + connection.on('end', function() { + connection.end(); + }); +}); +echoServer.listen(common.PORT); + +echoServer.on('listening', function() { + var clientConnection = net.createConnection(common.PORT); + clientConnection.setTimeout(0); + + setTimeout(function() { + // make sure both connections are still open + assert.equal(serverConnection.readyState, 'open'); + assert.equal(clientConnection.readyState, 'open'); + serverConnection.end(); + clientConnection.end(); + echoServer.close(); + }, 1200); +}); diff --git a/test/parallel/test-net-large-string.js b/test/parallel/test-net-large-string.js new file mode 100644 index 000000000..877dc7c78 --- /dev/null +++ b/test/parallel/test-net-large-string.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var kPoolSize = 40 * 1024; +var data = ''; +for (var i = 0; i < kPoolSize; ++i) { + data += 'あ'; // 3bytes +} +var receivedSize = 0; +var encoding = 'UTF-8'; + +var server = net.createServer(function(socket) { + socket.setEncoding(encoding); + socket.on('data', function(data) { + receivedSize += data.length; + }); + socket.on('end', function() { + socket.end(); + }); +}); + +server.listen(common.PORT, function() { + var client = net.createConnection(common.PORT); + client.on('end', function() { + server.close(); + }); + client.write(data, encoding); + client.end(); +}); + +process.on('exit', function() { + assert.equal(receivedSize, kPoolSize); +}); diff --git a/test/parallel/test-net-listen-close-server.js b/test/parallel/test-net-listen-close-server.js new file mode 100644 index 000000000..4a3233a8f --- /dev/null +++ b/test/parallel/test-net-listen-close-server.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var gotError = false; + +var server = net.createServer(function(socket) { +}); +server.listen(common.PORT, function() { + assert(false); +}); +server.on('error', function(error) { + common.debug(error); + assert(false); +}); +server.close(); diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js new file mode 100644 index 000000000..17ec762ca --- /dev/null +++ b/test/parallel/test-net-listen-error.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var gotError = false; + +var server = net.createServer(function(socket) { +}); +server.listen(1, '1.1.1.1', function() { // EACCESS or EADDRNOTAVAIL + assert(false); +}); +server.on('error', function(error) { + common.debug(error); + gotError = true; +}); + +process.on('exit', function() { + assert(gotError); +}); diff --git a/test/parallel/test-net-listen-fd0.js b/test/parallel/test-net-listen-fd0.js new file mode 100644 index 000000000..ac5896ee8 --- /dev/null +++ b/test/parallel/test-net-listen-fd0.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; + +process.on('exit', function() { + assert(gotError instanceof Error); +}); + +// this should fail with an async EINVAL error, not throw an exception +net.createServer(assert.fail).listen({fd:0}).on('error', function(e) { + switch(e.code) { + case 'EINVAL': + case 'ENOTSOCK': + gotError = e; + break + } +}); diff --git a/test/parallel/test-net-listen-shared-ports.js b/test/parallel/test-net-listen-shared-ports.js new file mode 100644 index 000000000..7422e491f --- /dev/null +++ b/test/parallel/test-net-listen-shared-ports.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +function noop() {} + +if (cluster.isMaster) { + var worker1 = cluster.fork(); + + worker1.on('message', function(msg) { + assert.equal(msg, 'success'); + var worker2 = cluster.fork(); + + worker2.on('message', function(msg) { + assert.equal(msg, 'server2:EADDRINUSE'); + worker1.kill(); + worker2.kill(); + }); + }); +} else { + var server1 = net.createServer(noop); + var server2 = net.createServer(noop); + + server1.on('error', function(err) { + // no errors expected + process.send('server1:' + err.code); + }); + + server2.on('error', function(err) { + // an error is expected on the second worker + process.send('server2:' + err.code); + }); + + server1.listen({ + host: 'localhost', + port: common.PORT, + exclusive: false + }, function() { + server2.listen({port: common.PORT + 1, exclusive: true}, function() { + // the first worker should succeed + process.send('success'); + }); + }); +} diff --git a/test/parallel/test-net-local-address-port.js b/test/parallel/test-net-local-address-port.js new file mode 100644 index 000000000..0f59cec9b --- /dev/null +++ b/test/parallel/test-net-local-address-port.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var conns = 0, conns_closed = 0; + +var server = net.createServer(function(socket) { + conns++; + assert.equal('127.0.0.1', socket.localAddress); + assert.equal(socket.localPort, common.PORT); + socket.on('end', function() { + server.close(); + }); + socket.resume(); +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var client = net.createConnection(common.PORT, '127.0.0.1'); + client.on('connect', function() { + client.end(); + }); +}); + +process.on('exit', function() { + assert.equal(1, conns); +}); diff --git a/test/parallel/test-net-localerror.js b/test/parallel/test-net-localerror.js new file mode 100644 index 000000000..c4d04aa92 --- /dev/null +++ b/test/parallel/test-net-localerror.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var server = net.createServer(function(socket) { + assert.ok(false, 'no clients should connect'); +}).listen(common.PORT).on('listening', function() { + server.unref(); + + function test1(next) { + connect({ + host: '127.0.0.1', + port: common.PORT, + localPort: 'foobar', + }, + 'localPort should be a number: foobar', + next); + } + + function test2(next) { + connect({ + host: '127.0.0.1', + port: common.PORT, + localAddress: 'foobar', + }, + 'localAddress should be a valid IP: foobar', + next) + } + + test1(test2); +}) + +function connect(opts, msg, cb) { + var client = net.connect(opts).on('connect', function() { + assert.ok(false, 'we should never connect'); + }).on('error', function(err) { + assert.strictEqual(err.message, msg); + if (cb) cb(); + }); +} diff --git a/test/parallel/test-net-pause-resume-connecting.js b/test/parallel/test-net-pause-resume-connecting.js new file mode 100644 index 000000000..264dc9680 --- /dev/null +++ b/test/parallel/test-net-pause-resume-connecting.js @@ -0,0 +1,101 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + net = require('net'); + +var connections = 0, + dataEvents = 0, + conn; + + +// Server +var server = net.createServer(function(conn) { + connections++; + conn.end('This was the year he fell to pieces.'); + + if (connections === 5) + server.close(); +}); + +server.listen(common.PORT); + + +// Client 1 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.resume(); +conn.on('data', onDataOk); + + +// Client 2 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.pause(); +conn.resume(); +conn.on('data', onDataOk); + + +// Client 3 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.pause(); +conn.on('data', onDataError); +scheduleTearDown(conn); + + +// Client 4 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.resume(); +conn.pause(); +conn.resume(); +conn.on('data', onDataOk); + + +// Client 5 +conn = require('net').createConnection(common.PORT, 'localhost'); +conn.resume(); +conn.resume(); +conn.pause(); +conn.on('data', onDataError); +scheduleTearDown(conn); + + +// Client helper functions +function onDataError() { + assert(false); +} + +function onDataOk() { + dataEvents++; +} + +function scheduleTearDown(conn) { + setTimeout(function() { + conn.removeAllListeners('data'); + conn.resume(); + }, 100); +} + + +// Exit sanity checks +process.on('exit', function() { + assert.strictEqual(connections, 5); + assert.strictEqual(dataEvents, 3); +}); diff --git a/test/parallel/test-net-pingpong.js b/test/parallel/test-net-pingpong.js new file mode 100644 index 000000000..ff7c97a03 --- /dev/null +++ b/test/parallel/test-net-pingpong.js @@ -0,0 +1,147 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var tests_run = 0; + +function pingPongTest(port, host) { + var N = 1000; + var count = 0; + var sentPongs = 0; + var sent_final_ping = false; + + var server = net.createServer({ allowHalfOpen: true }, function(socket) { + console.log('connection: ' + socket.remoteAddress); + assert.equal(server, socket.server); + assert.equal(1, server.connections); + + socket.setNoDelay(); + socket.timeout = 0; + + socket.setEncoding('utf8'); + socket.on('data', function(data) { + // Since we never queue data (we're always waiting for the PING + // before sending a pong) the writeQueueSize should always be less + // than one message. + assert.ok(0 <= socket.bufferSize && socket.bufferSize <= 4); + + console.log('server got: ' + data); + assert.equal(true, socket.writable); + assert.equal(true, socket.readable); + assert.equal(true, count <= N); + if (/PING/.exec(data)) { + socket.write('PONG', function() { + sentPongs++; + console.error('sent PONG'); + }); + } + }); + + socket.on('end', function() { + console.error(socket); + assert.equal(true, socket.allowHalfOpen); + assert.equal(true, socket.writable); // because allowHalfOpen + assert.equal(false, socket.readable); + socket.end(); + }); + + socket.on('error', function(e) { + throw e; + }); + + socket.on('close', function() { + console.log('server socket.endd'); + assert.equal(false, socket.writable); + assert.equal(false, socket.readable); + socket.server.close(); + }); + }); + + + server.listen(port, host, function() { + console.log('server listening on ' + port + ' ' + host); + + var client = net.createConnection(port, host); + + client.setEncoding('ascii'); + client.on('connect', function() { + assert.equal(true, client.readable); + assert.equal(true, client.writable); + client.write('PING'); + }); + + client.on('data', function(data) { + console.log('client got: ' + data); + + assert.equal('PONG', data); + count += 1; + + if (sent_final_ping) { + assert.equal(false, client.writable); + assert.equal(true, client.readable); + return; + } else { + assert.equal(true, client.writable); + assert.equal(true, client.readable); + } + + if (count < N) { + client.write('PING'); + } else { + sent_final_ping = true; + client.write('PING'); + client.end(); + } + }); + + client.on('close', function() { + console.log('client.end'); + assert.equal(N + 1, count); + assert.equal(N + 1, sentPongs); + assert.equal(true, sent_final_ping); + tests_run += 1; + }); + + client.on('error', function(e) { + throw e; + }); + }); +} + +/* All are run at once, so run on different ports */ +console.log(common.PIPE); +pingPongTest(common.PIPE); +pingPongTest(common.PORT); +pingPongTest(common.PORT + 1, 'localhost'); +if (common.hasIPv6) + pingPongTest(common.PORT + 2, '::1'); + +process.on('exit', function() { + if (common.hasIPv6) + assert.equal(4, tests_run); + else + assert.equal(3, tests_run); + console.log('done'); +}); diff --git a/test/parallel/test-net-pipe-connect-errors.js b/test/parallel/test-net-pipe-connect-errors.js new file mode 100644 index 000000000..07dd4fe4a --- /dev/null +++ b/test/parallel/test-net-pipe-connect-errors.js @@ -0,0 +1,110 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var fs = require('fs'); +var net = require('net'); +var path = require('path'); +var assert = require('assert'); +var common = require('../common'); + +var notSocketErrorFired = false; +var noEntErrorFired = false; +var accessErrorFired = false; + +// Test if ENOTSOCK is fired when trying to connect to a file which is not +// a socket. + +var emptyTxt; + +if (process.platform === 'win32') { + // on Win, common.PIPE will be a named pipe, so we use an existing empty + // file instead + emptyTxt = path.join(common.fixturesDir, 'empty.txt'); +} else { + // use common.PIPE to ensure we stay within POSIX socket path length + // restrictions, even on CI + emptyTxt = common.PIPE + '.txt'; + + function cleanup() { + try { + fs.unlinkSync(emptyTxt); + } catch (e) { + if (e.code != 'ENOENT') + throw e; + } + } + process.on('exit', cleanup); + cleanup(); + fs.writeFileSync(emptyTxt, ''); +} + +var notSocketClient = net.createConnection(emptyTxt, function() { + assert.ok(false); +}); + +notSocketClient.on('error', function(err) { + assert(err.code === 'ENOTSOCK' || err.code === 'ECONNREFUSED'); + notSocketErrorFired = true; +}); + + +// Trying to connect to not-existing socket should result in ENOENT error +var noEntSocketClient = net.createConnection('no-ent-file', function() { + assert.ok(false); +}); + +noEntSocketClient.on('error', function(err) { + assert.equal(err.code, 'ENOENT'); + noEntErrorFired = true; +}); + + +// On Windows or when running as root, a chmod has no effect on named pipes +if (process.platform !== 'win32' && process.getuid() !== 0) { + // Trying to connect to a socket one has no access to should result in EACCES + var accessServer = net.createServer(function() { + assert.ok(false); + }); + accessServer.listen(common.PIPE, function() { + fs.chmodSync(common.PIPE, 0); + + var accessClient = net.createConnection(common.PIPE, function() { + assert.ok(false); + }); + + accessClient.on('error', function(err) { + assert.equal(err.code, 'EACCES'); + accessErrorFired = true; + accessServer.close(); + }); + }); +} + + +// Assert that all error events were fired +process.on('exit', function() { + assert.ok(notSocketErrorFired); + assert.ok(noEntErrorFired); + if (process.platform !== 'win32' && process.getuid() !== 0) { + assert.ok(accessErrorFired); + } +}); + diff --git a/test/parallel/test-net-reconnect-error.js b/test/parallel/test-net-reconnect-error.js new file mode 100644 index 000000000..6094e943c --- /dev/null +++ b/test/parallel/test-net-reconnect-error.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); +var N = 50; +var client_error_count = 0; +var disconnect_count = 0; + +// Hopefully nothing is running on common.PORT +var c = net.createConnection(common.PORT); + +c.on('connect', function() { + console.error('CLIENT connected'); + assert.ok(false); +}); + +c.on('error', function(e) { + console.error('CLIENT error: ' + e.code); + client_error_count++; + assert.equal('ECONNREFUSED', e.code); +}); + +c.on('close', function() { + console.log('CLIENT disconnect'); + if (disconnect_count++ < N) + c.connect(common.PORT); // reconnect +}); + +process.on('exit', function() { + assert.equal(N + 1, disconnect_count); + assert.equal(N + 1, client_error_count); +}); diff --git a/test/parallel/test-net-reconnect.js b/test/parallel/test-net-reconnect.js new file mode 100644 index 000000000..ffc2a73c6 --- /dev/null +++ b/test/parallel/test-net-reconnect.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var N = 50; +var c = 0; +var client_recv_count = 0; +var client_end_count = 0; +var disconnect_count = 0; + +var server = net.createServer(function(socket) { + console.error('SERVER: got socket connection'); + socket.resume(); + + console.error('SERVER connect, writing'); + socket.write('hello\r\n'); + + socket.on('end', function() { + console.error('SERVER socket end, calling end()'); + socket.end(); + }); + + socket.on('close', function(had_error) { + console.log('SERVER had_error: ' + JSON.stringify(had_error)); + assert.equal(false, had_error); + }); +}); + +server.listen(common.PORT, function() { + console.log('SERVER listening'); + var client = net.createConnection(common.PORT); + + client.setEncoding('UTF8'); + + client.on('connect', function() { + console.error('CLIENT connected', client._writableState); + }); + + client.on('data', function(chunk) { + client_recv_count += 1; + console.log('client_recv_count ' + client_recv_count); + assert.equal('hello\r\n', chunk); + console.error('CLIENT: calling end', client._writableState); + client.end(); + }); + + client.on('end', function() { + console.error('CLIENT end'); + client_end_count++; + }); + + client.on('close', function(had_error) { + console.log('CLIENT disconnect'); + assert.equal(false, had_error); + if (disconnect_count++ < N) + client.connect(common.PORT); // reconnect + else + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(N + 1, disconnect_count); + assert.equal(N + 1, client_recv_count); + assert.equal(N + 1, client_end_count); +}); + diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js new file mode 100644 index 000000000..0cfe47afe --- /dev/null +++ b/test/parallel/test-net-remote-address-port.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var conns = 0, conns_closed = 0; + +var remoteAddrCandidates = [ '127.0.0.1']; +if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1'); + +var remoteFamilyCandidates = ['IPv4']; +if (common.hasIPv6) remoteFamilyCandidates.push('IPv6'); + +var server = net.createServer(function(socket) { + conns++; + assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); + assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); + assert.ok(socket.remotePort); + assert.notEqual(socket.remotePort, common.PORT); + socket.on('end', function() { + if (++conns_closed == 2) server.close(); + }); + socket.resume(); +}); + +server.listen(common.PORT, 'localhost', function() { + var client = net.createConnection(common.PORT, 'localhost'); + var client2 = net.createConnection(common.PORT); + client.on('connect', function() { + assert.notEqual(-1, remoteAddrCandidates.indexOf(client.remoteAddress)); + assert.notEqual(-1, remoteFamilyCandidates.indexOf(client.remoteFamily)); + assert.equal(common.PORT, client.remotePort); + client.end(); + }); + client2.on('connect', function() { + assert.notEqual(-1, remoteAddrCandidates.indexOf(client2.remoteAddress)); + assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); + assert.equal(common.PORT, client2.remotePort); + client2.end(); + }); +}); + +process.on('exit', function() { + assert.equal(2, conns); +}); diff --git a/test/parallel/test-net-server-close.js b/test/parallel/test-net-server-close.js new file mode 100644 index 000000000..afa83f10d --- /dev/null +++ b/test/parallel/test-net-server-close.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var events = []; +var sockets = []; + +process.on('exit', function() { + assert.equal(server.connections, 0); + assert.equal(events.length, 3); + // Expect to see one server event and two client events. The order of the + // events is undefined because they arrive on the same event loop tick. + assert.equal(events.join(' ').match(/server/g).length, 1); + assert.equal(events.join(' ').match(/client/g).length, 2); +}); + +var server = net.createServer(function(c) { + c.on('close', function() { + events.push('client'); + }); + + sockets.push(c); + + if (sockets.length === 2) { + server.close(); + sockets.forEach(function(c) { c.destroy() }); + } +}); + +server.on('close', function() { + events.push('server'); +}); + +server.listen(common.PORT, function() { + net.createConnection(common.PORT); + net.createConnection(common.PORT); +}); diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js new file mode 100644 index 000000000..423fcb8e3 --- /dev/null +++ b/test/parallel/test-net-server-connections.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +// test that server.connections property is no longer enumerable now that it +// has been marked as deprecated + +var server = new net.Server(); + +assert.equal(Object.keys(server).indexOf('connections'), -1); diff --git a/test/parallel/test-net-server-listen-remove-callback.js b/test/parallel/test-net-server-listen-remove-callback.js new file mode 100644 index 000000000..e10231de8 --- /dev/null +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +// Server should only fire listen callback once +var server = net.createServer(); + +server.on('close', function() { + var listeners = server.listeners('listening'); + console.log('Closed, listeners:', listeners.length); + assert.equal(0, listeners.length); +}); + +server.listen(common.PORT, function() { + server.close(); +}); + +server.once('close', function() { + server.listen(common.PORT + 1, function() { + server.close(); + }); +}); diff --git a/test/parallel/test-net-server-max-connections.js b/test/parallel/test-net-server-max-connections.js new file mode 100644 index 000000000..43bc2fee1 --- /dev/null +++ b/test/parallel/test-net-server-max-connections.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +// This test creates 200 connections to a server and sets the server's +// maxConnections property to 100. The first 100 connections make it through +// and the last 100 connections are rejected. +// TODO: test that the server can accept more connections after it reaches +// its maximum and some are closed. + +var N = 200; +var count = 0; +var closes = 0; +var waits = []; + +var server = net.createServer(function(connection) { + console.error('connect %d', count++); + connection.write('hello'); + waits.push(function() { connection.end(); }); +}); + +server.listen(common.PORT, function() { + makeConnection(0); +}); + +server.maxConnections = N / 2; + +console.error('server.maxConnections = %d', server.maxConnections); + + +function makeConnection(index) { + var c = net.createConnection(common.PORT); + var gotData = false; + + c.on('connect', function() { + if (index + 1 < N) { + makeConnection(index + 1); + } + }); + + c.on('end', function() { c.end(); }); + + c.on('data', function(b) { + gotData = true; + assert.ok(0 < b.length); + }); + + c.on('error', function(e) { + console.error('error %d: %s', index, e); + }); + + c.on('close', function() { + console.error('closed %d', index); + closes++; + + if (closes < N / 2) { + assert.ok(server.maxConnections <= index, + index + + ' was one of the first closed connections ' + + 'but shouldnt have been'); + } + + if (closes === N / 2) { + var cb; + console.error('calling wait callback.'); + while (cb = waits.shift()) { + cb(); + } + server.close(); + } + + if (index < server.maxConnections) { + assert.equal(true, gotData, + index + ' didn\'t get data, but should have'); + } else { + assert.equal(false, gotData, + index + ' got data, but shouldn\'t have'); + } + }); +} + + +process.on('exit', function() { + assert.equal(N, closes); +}); diff --git a/test/parallel/test-net-server-pause-on-connect.js b/test/parallel/test-net-server-pause-on-connect.js new file mode 100644 index 000000000..3a8255e8f --- /dev/null +++ b/test/parallel/test-net-server-pause-on-connect.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var msg = 'test'; +var stopped = true; +var server1 = net.createServer({pauseOnConnect: true}, function(socket) { + socket.on('data', function(data) { + if (stopped) { + assert(false, 'data event should not have happened yet'); + } + + assert.equal(data.toString(), msg, 'invalid data received'); + socket.end(); + server1.close(); + }); + + setTimeout(function() { + assert.equal(socket.bytesRead, 0, 'no data should have been read yet'); + socket.resume(); + stopped = false; + }, 3000); +}); + +var server2 = net.createServer({pauseOnConnect: false}, function(socket) { + socket.on('data', function(data) { + assert.equal(data.toString(), msg, 'invalid data received'); + socket.end(); + server2.close(); + }); +}); + +server1.listen(common.PORT, function() { + net.createConnection({port: common.PORT}).write(msg); +}); + +server2.listen(common.PORT + 1, function() { + net.createConnection({port: common.PORT + 1}).write(msg); +}); diff --git a/test/parallel/test-net-server-try-ports.js b/test/parallel/test-net-server-try-ports.js new file mode 100644 index 000000000..5eca9d095 --- /dev/null +++ b/test/parallel/test-net-server-try-ports.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests binds to one port, then attempts to start a server on that +// port. It should be EADDRINUSE but be able to then bind to another port. +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var connections = 0; + +var server1listening = false; +var server2listening = false; + +var server1 = net.Server(function(socket) { + connections++; + socket.destroy(); +}); + +var server2 = net.Server(function(socket) { + connections++; + socket.destroy(); +}); + +var server2errors = 0; +server2.on('error', function() { + server2errors++; + console.error('server2 error'); +}); + + +server1.listen(common.PORT, function() { + console.error('server1 listening'); + server1listening = true; + // This should make server2 emit EADDRINUSE + server2.listen(common.PORT); + + // Wait a bit, now try again. + // TODO, the listen callback should report if there was an error. + // Then we could avoid this very unlikely but potential race condition + // here. + setTimeout(function() { + server2.listen(common.PORT + 1, function() { + console.error('server2 listening'); + server2listening = true; + + server1.close(); + server2.close(); + }); + }, 100); +}); + + +process.on('exit', function() { + assert.equal(1, server2errors); + assert.ok(server2listening); + assert.ok(server1listening); +}); diff --git a/test/parallel/test-net-server-unref.js b/test/parallel/test-net-server-unref.js new file mode 100644 index 000000000..f7f994bab --- /dev/null +++ b/test/parallel/test-net-server-unref.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); +var closed = false; + +var s = net.createServer(); +s.listen(common.PORT); +s.unref(); + +setTimeout(function() { + closed = true; + s.close(); +}, 1000).unref(); + +process.on('exit', function() { + assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); +}); diff --git a/test/parallel/test-net-settimeout.js b/test/parallel/test-net-settimeout.js new file mode 100644 index 000000000..da13385b9 --- /dev/null +++ b/test/parallel/test-net-settimeout.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This example sets a timeout then immediately attempts to disable the timeout +// https://github.com/joyent/node/pull/2245 + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var T = 100; + +var server = net.createServer(function(c) { + c.write('hello'); +}); +server.listen(common.PORT); + +var killers = [0, Infinity, NaN]; + +var left = killers.length; +killers.forEach(function(killer) { + var socket = net.createConnection(common.PORT, 'localhost'); + + socket.setTimeout(T, function() { + socket.destroy(); + if (--left === 0) server.close(); + assert.ok(killer !== 0); + clearTimeout(timeout); + }); + + socket.setTimeout(killer); + + var timeout = setTimeout(function() { + socket.destroy(); + if (--left === 0) server.close(); + assert.ok(killer === 0); + }, T * 2); +}); diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js new file mode 100644 index 000000000..882e3a14c --- /dev/null +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var nerrors = 0; +var ncloses = 0; + +process.on('exit', function() { + assert.equal(nerrors, 1); + assert.equal(ncloses, 1); +}); + +var conn = net.createConnection(common.PORT); + +conn.on('error', function() { + nerrors++; + conn.destroy(); +}); + +conn.on('close', function() { + ncloses++; +}); diff --git a/test/parallel/test-net-socket-timeout-unref.js b/test/parallel/test-net-socket-timeout-unref.js new file mode 100644 index 000000000..32aef444a --- /dev/null +++ b/test/parallel/test-net-socket-timeout-unref.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var server = net.createServer(function (c) { + c.write('hello'); + c.unref(); +}); +server.listen(common.PORT); +server.unref(); + +var timedout = false; + +[8, 5, 3, 6, 2, 4].forEach(function (T) { + var socket = net.createConnection(common.PORT, 'localhost'); + socket.setTimeout(T * 1000, function () { + console.log(process._getActiveHandles()); + timedout = true; + socket.destroy(); + }); + socket.unref(); +}); + +process.on('exit', function () { + assert.strictEqual(timedout, false, 'Socket timeout should not hold loop open'); +}); diff --git a/test/parallel/test-net-socket-timeout.js b/test/parallel/test-net-socket-timeout.js new file mode 100644 index 000000000..2256d6813 --- /dev/null +++ b/test/parallel/test-net-socket-timeout.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +var timedout = false; + +var server = net.Server(); +server.listen(common.PORT, function() { + var socket = net.createConnection(common.PORT); + socket.setTimeout(100, function() { + timedout = true; + socket.destroy(); + server.close(); + clearTimeout(timer); + }); + var timer = setTimeout(function() { + process.exit(1); + }, 200); +}); + +process.on('exit', function() { + assert.ok(timedout); +}); diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js new file mode 100644 index 000000000..9f2db51be --- /dev/null +++ b/test/parallel/test-net-stream.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); + +var s = new net.Stream(); + +// test that destroy called on a stream with a server only ever decrements the +// server connection count once + +s.server = new net.Server(); +s.server.connections = 10; + +assert.equal(10, s.server.connections); +s.destroy(); +assert.equal(9, s.server.connections); +s.destroy(); +assert.equal(9, s.server.connections); + +var SIZE = 2E6; +var N = 10; +var buf = new Buffer(SIZE); +buf.fill(0x61); // 'a' + +var server = net.createServer(function(socket) { + socket.setNoDelay(); + + socket.on('error', function(err) { + socket.destroy(); + }).on('close', function() { + server.close(); + }) + + for (var i = 0; i < N; ++i) { + socket.write(buf, function() { }); + } + socket.end(); + +}).listen(common.PORT, function() { + var conn = net.connect(common.PORT); + conn.on('data', function(buf) { + conn.pause(); + setTimeout(function() { + conn.destroy(); + }, 20); + }); + }); + +process.on('exit', function() { + assert.equal(server.connections, 0); +}); diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js new file mode 100644 index 000000000..3b98bbc42 --- /dev/null +++ b/test/parallel/test-net-write-after-close.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var gotError = false; +var gotWriteCB = false; + +process.on('exit', function() { + assert(gotError); + assert(gotWriteCB); +}); + +var server = net.createServer(function(socket) { + socket.resume(); + + socket.on('error', function(error) { + console.error('got error, closing server', error); + server.close(); + gotError = true; + }); + + setTimeout(function() { + console.error('about to try to write'); + socket.write('test', function(e) { + gotWriteCB = true; + }); + }, 250); +}); + +server.listen(common.PORT, function() { + var client = net.connect(common.PORT, function() { + client.end(); + }); +}); diff --git a/test/parallel/test-net-write-connect-write.js b/test/parallel/test-net-write-connect-write.js new file mode 100644 index 000000000..cb65af8a8 --- /dev/null +++ b/test/parallel/test-net-write-connect-write.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var received = ''; + +var server = net.createServer(function(socket) { + socket.pipe(socket); +}).listen(common.PORT, function() { + var conn = net.connect(common.PORT); + conn.setEncoding('utf8'); + conn.write('before'); + conn.on('connect', function() { + conn.write('after'); + }); + conn.on('data', function(buf) { + received += buf; + conn.end(); + }); + conn.on('end', function() { + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(received, 'before' + 'after'); +}); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js new file mode 100644 index 000000000..468c311c5 --- /dev/null +++ b/test/parallel/test-net-write-slow.js @@ -0,0 +1,67 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var SIZE = 2E5; +var N = 10; +var flushed = 0; +var received = 0; +var buf = new Buffer(SIZE); +buf.fill(0x61); // 'a' + +var server = net.createServer(function(socket) { + socket.setNoDelay(); + socket.setTimeout(1000); + socket.on('timeout', function() { + assert.fail('flushed: ' + flushed + + ', received: ' + received + '/' + SIZE * N); + }); + + for (var i = 0; i < N; ++i) { + socket.write(buf, function() { + ++flushed; + if (flushed === N) { + socket.setTimeout(0); + } + }); + } + socket.end(); + +}).listen(common.PORT, function() { + var conn = net.connect(common.PORT); + conn.on('data', function(buf) { + received += buf.length; + conn.pause(); + setTimeout(function() { + conn.resume(); + }, 20); + }); + conn.on('end', function() { + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(received, SIZE * N); +}); diff --git a/test/parallel/test-next-tick-doesnt-hang.js b/test/parallel/test-next-tick-doesnt-hang.js new file mode 100644 index 000000000..3d26bd3c6 --- /dev/null +++ b/test/parallel/test-next-tick-doesnt-hang.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +/* + * This test verifies that having a single nextTick statement and nothing else + * does not hang the event loop. If this test times out it has failed. + */ + +process.nextTick(function() { + // Nothing +}); diff --git a/test/parallel/test-next-tick-domain.js b/test/parallel/test-next-tick-domain.js new file mode 100644 index 000000000..16f77ed94 --- /dev/null +++ b/test/parallel/test-next-tick-domain.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var origNextTick = process.nextTick; + +require('domain'); + +assert.strictEqual(origNextTick, process.nextTick, 'Requiring domain should not change nextTick'); diff --git a/test/parallel/test-next-tick-errors.js b/test/parallel/test-next-tick-errors.js new file mode 100644 index 000000000..bf3c2e306 --- /dev/null +++ b/test/parallel/test-next-tick-errors.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var order = [], + exceptionHandled = false; + +// This nextTick function will throw an error. It should only be called once. +// When it throws an error, it should still get removed from the queue. +process.nextTick(function() { + order.push('A'); + // cause an error + what(); +}); + +// This nextTick function should remain in the queue when the first one +// is removed. It should be called if the error in the first one is +// caught (which we do in this test). +process.nextTick(function() { + order.push('C'); +}); + +process.on('uncaughtException', function() { + if (!exceptionHandled) { + exceptionHandled = true; + order.push('B'); + } + else { + // If we get here then the first process.nextTick got called twice + order.push('OOPS!'); + } +}); + +process.on('exit', function() { + assert.deepEqual(['A', 'B', 'C'], order); +}); + diff --git a/test/parallel/test-next-tick-intentional-starvation.js b/test/parallel/test-next-tick-intentional-starvation.js new file mode 100644 index 000000000..1a76b27e4 --- /dev/null +++ b/test/parallel/test-next-tick-intentional-starvation.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// this is the inverse of test-next-tick-starvation. +// it verifies that process.nextTick will *always* come before other +// events, up to the limit of the process.maxTickDepth value. + +// WARNING: unsafe! +process.maxTickDepth = Infinity; + +var ran = false; +var starved = false; +var start = +new Date(); +var timerRan = false; + +function spin() { + ran = true; + var now = +new Date(); + if (now - start > 100) { + console.log('The timer is starving, just as we planned.'); + starved = true; + + // now let it out. + return; + } + + process.nextTick(spin); +} + +function onTimeout() { + if (!starved) throw new Error('The timer escaped!'); + console.log('The timer ran once the ban was lifted'); + timerRan = true; +} + +spin(); +setTimeout(onTimeout, 50); + +process.on('exit', function() { + assert.ok(ran); + assert.ok(starved); + assert.ok(timerRan); +}); diff --git a/test/parallel/test-next-tick-ordering.js b/test/parallel/test-next-tick-ordering.js new file mode 100644 index 000000000..5dc1dfbe1 --- /dev/null +++ b/test/parallel/test-next-tick-ordering.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var i; + +var N = 30; +var done = []; + +function get_printer(timeout) { + return function() { + console.log('Running from setTimeout ' + timeout); + done.push(timeout); + }; +} + +process.nextTick(function() { + console.log('Running from nextTick'); + done.push('nextTick'); +}); + +for (i = 0; i < N; i += 1) { + setTimeout(get_printer(i), i); +} + +console.log('Running from main.'); + + +process.on('exit', function() { + assert.equal('nextTick', done[0]); + /* Disabling this test. I don't think we can ensure the order + for (i = 0; i < N; i += 1) { + assert.equal(i, done[i + 1]); + } + */ +}); diff --git a/test/parallel/test-next-tick-ordering2.js b/test/parallel/test-next-tick-ordering2.js new file mode 100644 index 000000000..94fd20fbb --- /dev/null +++ b/test/parallel/test-next-tick-ordering2.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var order = []; +process.nextTick(function() { + setTimeout(function() { + order.push('setTimeout'); + }, 0); + + process.nextTick(function() { + order.push('nextTick'); + }); +}); + +process.on('exit', function() { + assert.deepEqual(order, ['nextTick', 'setTimeout']); +}); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js new file mode 100644 index 000000000..2e40658c9 --- /dev/null +++ b/test/parallel/test-next-tick.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var complete = 0; + +process.nextTick(function() { + complete++; + process.nextTick(function() { + complete++; + process.nextTick(function() { + complete++; + }); + }); +}); + +setTimeout(function() { + process.nextTick(function() { + complete++; + }); +}, 50); + +process.nextTick(function() { + complete++; +}); + +process.on('exit', function() { + assert.equal(5, complete); + process.nextTick(function() { + throw new Error('this should not occur'); + }); +}); diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js new file mode 100644 index 000000000..5763e071b --- /dev/null +++ b/test/parallel/test-os.js @@ -0,0 +1,112 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var os = require('os'); + + +process.env.TMPDIR = '/tmpdir'; +process.env.TMP = '/tmp'; +process.env.TEMP = '/temp'; +if (process.platform === 'win32') { + assert.equal(os.tmpdir(), '/temp'); + process.env.TEMP = ''; + assert.equal(os.tmpdir(), '/tmp'); + process.env.TMP = ''; + var expected = (process.env.SystemRoot || process.env.windir) + '\\temp'; + assert.equal(os.tmpdir(), expected); +} else { + assert.equal(os.tmpdir(), '/tmpdir'); + process.env.TMPDIR = ''; + assert.equal(os.tmpdir(), '/tmp'); + process.env.TMP = ''; + assert.equal(os.tmpdir(), '/temp'); + process.env.TEMP = ''; + assert.equal(os.tmpdir(), '/tmp'); +} + +var endianness = os.endianness(); +console.log('endianness = %s', endianness); +assert.ok(/[BL]E/.test(endianness)); + +var hostname = os.hostname(); +console.log('hostname = %s', hostname); +assert.ok(hostname.length > 0); + +var uptime = os.uptime(); +console.log('uptime = %d', uptime); +assert.ok(uptime > 0); + +var cpus = os.cpus(); +console.log('cpus = ', cpus); +assert.ok(cpus.length > 0); + +var type = os.type(); +console.log('type = ', type); +assert.ok(type.length > 0); + +var release = os.release(); +console.log('release = ', release); +assert.ok(release.length > 0); + +var platform = os.platform(); +console.log('platform = ', platform); +assert.ok(platform.length > 0); + +var arch = os.arch(); +console.log('arch = ', arch); +assert.ok(arch.length > 0); + +if (process.platform != 'sunos') { + // not implemeneted yet + assert.ok(os.loadavg().length > 0); + assert.ok(os.freemem() > 0); + assert.ok(os.totalmem() > 0); +} + + +var interfaces = os.networkInterfaces(); +console.error(interfaces); +switch (platform) { + case 'linux': + var filter = function(e) { return e.address == '127.0.0.1'; }; + var actual = interfaces.lo.filter(filter); + var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', + mac: '00:00:00:00:00:00', family: 'IPv4', + internal: true }]; + assert.deepEqual(actual, expected); + break; + case 'win32': + var filter = function(e) { return e.address == '127.0.0.1'; }; + var actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); + var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', + mac: '00:00:00:00:00:00', family: 'IPv4', + internal: true }]; + assert.deepEqual(actual, expected); + break; +} + +var EOL = os.EOL; +assert.ok(EOL.length > 0); diff --git a/test/parallel/test-path-makelong.js b/test/parallel/test-path-makelong.js new file mode 100644 index 000000000..d9d8efd40 --- /dev/null +++ b/test/parallel/test-path-makelong.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var path = require('path'); +var common = require('../common'); + +if (process.platform === 'win32') { + var file = path.join(common.fixturesDir, 'a.js'); + var resolvedFile = path.resolve(file); + + assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); + assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); + assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', + path._makeLong('\\\\someserver\\someshare\\somefile')); + assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', + path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); + assert.equal('\\\\.\\pipe\\somepipe', + path._makeLong('\\\\.\\pipe\\somepipe')); +} + +assert.equal(path._makeLong(null), null); +assert.equal(path._makeLong(100), 100); +assert.equal(path._makeLong(path), path); +assert.equal(path._makeLong(false), false); +assert.equal(path._makeLong(true), true); diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js new file mode 100644 index 000000000..4f6e5af45 --- /dev/null +++ b/test/parallel/test-path-parse-format.js @@ -0,0 +1,99 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var path = require('path'); + +var winPaths = [ + 'C:\\path\\dir\\index.html', + 'C:\\another_path\\DIR\\1\\2\\33\\index', + 'another_path\\DIR with spaces\\1\\2\\33\\index', + '\\foo\\C:', + 'file', + '.\\file', + + // unc + '\\\\server\\share\\file_path', + '\\\\server two\\shared folder\\file path.zip', + '\\\\teela\\admin$\\system32', + '\\\\?\\UNC\\server\\share' + +]; + +var unixPaths = [ + '/home/user/dir/file.txt', + '/home/user/a dir/another File.zip', + '/home/user/a dir//another&File.', + '/home/user/a$$$dir//another File.zip', + 'user/dir/another File.zip', + 'file', + '.\\file', + './file', + 'C:\\foo' +]; + +var errors = [ + {method: 'parse', input: [null], message: /Parameter 'pathString' must be a string, not/}, + {method: 'parse', input: [{}], message: /Parameter 'pathString' must be a string, not object/}, + {method: 'parse', input: [true], message: /Parameter 'pathString' must be a string, not boolean/}, + {method: 'parse', input: [1], message: /Parameter 'pathString' must be a string, not number/}, + {method: 'parse', input: [], message: /Parameter 'pathString' must be a string, not undefined/}, + // {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger! + {method: 'format', input: [null], message: /Parameter 'pathObject' must be an object, not/}, + {method: 'format', input: [''], message: /Parameter 'pathObject' must be an object, not string/}, + {method: 'format', input: [true], message: /Parameter 'pathObject' must be an object, not boolean/}, + {method: 'format', input: [1], message: /Parameter 'pathObject' must be an object, not number/}, + {method: 'format', input: [{root: true}], message: /'pathObject.root' must be a string or undefined, not boolean/}, + {method: 'format', input: [{root: 12}], message: /'pathObject.root' must be a string or undefined, not number/}, +]; + +check(path.win32, winPaths); +check(path.posix, unixPaths); +checkErrors(path.win32); +checkErrors(path.posix); + +function checkErrors(path) { + errors.forEach(function(errorCase) { + try { + path[errorCase.method].apply(path, errorCase.input); + } catch(err) { + assert.ok(err instanceof TypeError); + assert.ok( + errorCase.message.test(err.message), + 'expected ' + errorCase.message + ' to match ' + err.message + ); + return; + } + + assert.fail('should have thrown'); + }); +} + + +function check(path, paths) { + paths.forEach(function(element, index, array) { + var output = path.parse(element); + assert.strictEqual(path.format(output), element); + assert.strictEqual(output.dir, output.dir ? path.dirname(element) : ''); + assert.strictEqual(output.base, path.basename(element)); + assert.strictEqual(output.ext, path.extname(element)); + }); +} diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js new file mode 100644 index 000000000..45fd282d0 --- /dev/null +++ b/test/parallel/test-path.js @@ -0,0 +1,412 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var path = require('path'); + +var isWindows = process.platform === 'win32'; + +var f = __filename; + +assert.equal(path.basename(f), 'test-path.js'); +assert.equal(path.basename(f, '.js'), 'test-path'); +assert.equal(path.basename(''), ''); +assert.equal(path.basename('/dir/basename.ext'), 'basename.ext'); +assert.equal(path.basename('/basename.ext'), 'basename.ext'); +assert.equal(path.basename('basename.ext'), 'basename.ext'); +assert.equal(path.basename('basename.ext/'), 'basename.ext'); +assert.equal(path.basename('basename.ext//'), 'basename.ext'); + +// On Windows a backslash acts as a path separator. +assert.equal(path.win32.basename('\\dir\\basename.ext'), 'basename.ext'); +assert.equal(path.win32.basename('\\basename.ext'), 'basename.ext'); +assert.equal(path.win32.basename('basename.ext'), 'basename.ext'); +assert.equal(path.win32.basename('basename.ext\\'), 'basename.ext'); +assert.equal(path.win32.basename('basename.ext\\\\'), 'basename.ext'); + +// On unix a backslash is just treated as any other character. +assert.equal(path.posix.basename('\\dir\\basename.ext'), '\\dir\\basename.ext'); +assert.equal(path.posix.basename('\\basename.ext'), '\\basename.ext'); +assert.equal(path.posix.basename('basename.ext'), 'basename.ext'); +assert.equal(path.posix.basename('basename.ext\\'), 'basename.ext\\'); +assert.equal(path.posix.basename('basename.ext\\\\'), 'basename.ext\\\\'); + +// POSIX filenames may include control characters +// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html +if (!isWindows) { + var controlCharFilename = 'Icon' + String.fromCharCode(13); + assert.equal(path.basename('/a/b/' + controlCharFilename), + controlCharFilename); +} + +assert.equal(path.extname(f), '.js'); + +assert.equal(path.dirname(f).substr(-13), + isWindows ? 'test\\parallel' : 'test/parallel'); +assert.equal(path.dirname('/a/b/'), '/a'); +assert.equal(path.dirname('/a/b'), '/a'); +assert.equal(path.dirname('/a'), '/'); +assert.equal(path.dirname(''), '.'); +assert.equal(path.dirname('/'), '/'); +assert.equal(path.dirname('////'), '/'); + +assert.equal(path.win32.dirname('c:\\'), 'c:\\'); +assert.equal(path.win32.dirname('c:\\foo'), 'c:\\'); +assert.equal(path.win32.dirname('c:\\foo\\'), 'c:\\'); +assert.equal(path.win32.dirname('c:\\foo\\bar'), 'c:\\foo'); +assert.equal(path.win32.dirname('c:\\foo\\bar\\'), 'c:\\foo'); +assert.equal(path.win32.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar'); +assert.equal(path.win32.dirname('\\'), '\\'); +assert.equal(path.win32.dirname('\\foo'), '\\'); +assert.equal(path.win32.dirname('\\foo\\'), '\\'); +assert.equal(path.win32.dirname('\\foo\\bar'), '\\foo'); +assert.equal(path.win32.dirname('\\foo\\bar\\'), '\\foo'); +assert.equal(path.win32.dirname('\\foo\\bar\\baz'), '\\foo\\bar'); +assert.equal(path.win32.dirname('c:'), 'c:'); +assert.equal(path.win32.dirname('c:foo'), 'c:'); +assert.equal(path.win32.dirname('c:foo\\'), 'c:'); +assert.equal(path.win32.dirname('c:foo\\bar'), 'c:foo'); +assert.equal(path.win32.dirname('c:foo\\bar\\'), 'c:foo'); +assert.equal(path.win32.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); +assert.equal(path.win32.dirname('\\\\unc\\share'), '\\\\unc\\share'); +assert.equal(path.win32.dirname('\\\\unc\\share\\foo'), '\\\\unc\\share\\'); +assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\'), '\\\\unc\\share\\'); +assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar'), + '\\\\unc\\share\\foo'); +assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar\\'), + '\\\\unc\\share\\foo'); +assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar\\baz'), + '\\\\unc\\share\\foo\\bar'); + + +assert.equal(path.extname(''), ''); +assert.equal(path.extname('/path/to/file'), ''); +assert.equal(path.extname('/path/to/file.ext'), '.ext'); +assert.equal(path.extname('/path.to/file.ext'), '.ext'); +assert.equal(path.extname('/path.to/file'), ''); +assert.equal(path.extname('/path.to/.file'), ''); +assert.equal(path.extname('/path.to/.file.ext'), '.ext'); +assert.equal(path.extname('/path/to/f.ext'), '.ext'); +assert.equal(path.extname('/path/to/..ext'), '.ext'); +assert.equal(path.extname('file'), ''); +assert.equal(path.extname('file.ext'), '.ext'); +assert.equal(path.extname('.file'), ''); +assert.equal(path.extname('.file.ext'), '.ext'); +assert.equal(path.extname('/file'), ''); +assert.equal(path.extname('/file.ext'), '.ext'); +assert.equal(path.extname('/.file'), ''); +assert.equal(path.extname('/.file.ext'), '.ext'); +assert.equal(path.extname('.path/file.ext'), '.ext'); +assert.equal(path.extname('file.ext.ext'), '.ext'); +assert.equal(path.extname('file.'), '.'); +assert.equal(path.extname('.'), ''); +assert.equal(path.extname('./'), ''); +assert.equal(path.extname('.file.ext'), '.ext'); +assert.equal(path.extname('.file'), ''); +assert.equal(path.extname('.file.'), '.'); +assert.equal(path.extname('.file..'), '.'); +assert.equal(path.extname('..'), ''); +assert.equal(path.extname('../'), ''); +assert.equal(path.extname('..file.ext'), '.ext'); +assert.equal(path.extname('..file'), '.file'); +assert.equal(path.extname('..file.'), '.'); +assert.equal(path.extname('..file..'), '.'); +assert.equal(path.extname('...'), '.'); +assert.equal(path.extname('...ext'), '.ext'); +assert.equal(path.extname('....'), '.'); +assert.equal(path.extname('file.ext/'), '.ext'); +assert.equal(path.extname('file.ext//'), '.ext'); +assert.equal(path.extname('file/'), ''); +assert.equal(path.extname('file//'), ''); +assert.equal(path.extname('file./'), '.'); +assert.equal(path.extname('file.//'), '.'); + +// On windows, backspace is a path separator. +assert.equal(path.win32.extname('.\\'), ''); +assert.equal(path.win32.extname('..\\'), ''); +assert.equal(path.win32.extname('file.ext\\'), '.ext'); +assert.equal(path.win32.extname('file.ext\\\\'), '.ext'); +assert.equal(path.win32.extname('file\\'), ''); +assert.equal(path.win32.extname('file\\\\'), ''); +assert.equal(path.win32.extname('file.\\'), '.'); +assert.equal(path.win32.extname('file.\\\\'), '.'); + +// On unix, backspace is a valid name component like any other character. +assert.equal(path.posix.extname('.\\'), ''); +assert.equal(path.posix.extname('..\\'), '.\\'); +assert.equal(path.posix.extname('file.ext\\'), '.ext\\'); +assert.equal(path.posix.extname('file.ext\\\\'), '.ext\\\\'); +assert.equal(path.posix.extname('file\\'), ''); +assert.equal(path.posix.extname('file\\\\'), ''); +assert.equal(path.posix.extname('file.\\'), '.\\'); +assert.equal(path.posix.extname('file.\\\\'), '.\\\\'); + +// path.join tests +var failures = []; +var joinTests = + // arguments result + [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], + [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], + [['/foo', '../../../bar'], '/bar'], + [['foo', '../../../bar'], '../../bar'], + [['foo/', '../../../bar'], '../../bar'], + [['foo/x', '../../../bar'], '../bar'], + [['foo/x', './bar'], 'foo/x/bar'], + [['foo/x/', './bar'], 'foo/x/bar'], + [['foo/x/', '.', 'bar'], 'foo/x/bar'], + [['./'], './'], + [['.', './'], './'], + [['.', '.', '.'], '.'], + [['.', './', '.'], '.'], + [['.', '/./', '.'], '.'], + [['.', '/////./', '.'], '.'], + [['.'], '.'], + [['', '.'], '.'], + [['', 'foo'], 'foo'], + [['foo', '/bar'], 'foo/bar'], + [['', '/foo'], '/foo'], + [['', '', '/foo'], '/foo'], + [['', '', 'foo'], 'foo'], + [['foo', ''], 'foo'], + [['foo/', ''], 'foo/'], + [['foo', '', '/bar'], 'foo/bar'], + [['./', '..', '/foo'], '../foo'], + [['./', '..', '..', '/foo'], '../../foo'], + [['.', '..', '..', '/foo'], '../../foo'], + [['', '..', '..', '/foo'], '../../foo'], + [['/'], '/'], + [['/', '.'], '/'], + [['/', '..'], '/'], + [['/', '..', '..'], '/'], + [[''], '.'], + [['', ''], '.'], + [[' /foo'], ' /foo'], + [[' ', 'foo'], ' /foo'], + [[' ', '.'], ' '], + [[' ', '/'], ' /'], + [[' ', ''], ' '], + [['/', 'foo'], '/foo'], + [['/', '/foo'], '/foo'], + [['/', '//foo'], '/foo'], + [['/', '', '/foo'], '/foo'], + [['', '/', 'foo'], '/foo'], + [['', '/', '/foo'], '/foo'] + ]; + +// Windows-specific join tests +if (isWindows) { + joinTests = joinTests.concat( + [// UNC path expected + [['//foo/bar'], '//foo/bar/'], + [['\\/foo/bar'], '//foo/bar/'], + [['\\\\foo/bar'], '//foo/bar/'], + // UNC path expected - server and share separate + [['//foo', 'bar'], '//foo/bar/'], + [['//foo/', 'bar'], '//foo/bar/'], + [['//foo', '/bar'], '//foo/bar/'], + // UNC path expected - questionable + [['//foo', '', 'bar'], '//foo/bar/'], + [['//foo/', '', 'bar'], '//foo/bar/'], + [['//foo/', '', '/bar'], '//foo/bar/'], + // UNC path expected - even more questionable + [['', '//foo', 'bar'], '//foo/bar/'], + [['', '//foo/', 'bar'], '//foo/bar/'], + [['', '//foo/', '/bar'], '//foo/bar/'], + // No UNC path expected (no double slash in first component) + [['\\', 'foo/bar'], '/foo/bar'], + [['\\', '/foo/bar'], '/foo/bar'], + [['', '/', '/foo/bar'], '/foo/bar'], + // No UNC path expected (no non-slashes in first component - questionable) + [['//', 'foo/bar'], '/foo/bar'], + [['//', '/foo/bar'], '/foo/bar'], + [['\\\\', '/', '/foo/bar'], '/foo/bar'], + [['//'], '/'], + // No UNC path expected (share name missing - questionable). + [['//foo'], '/foo'], + [['//foo/'], '/foo/'], + [['//foo', '/'], '/foo/'], + [['//foo', '', '/'], '/foo/'], + // No UNC path expected (too many leading slashes - questionable) + [['///foo/bar'], '/foo/bar'], + [['////foo', 'bar'], '/foo/bar'], + [['\\\\\\/foo/bar'], '/foo/bar'], + // Drive-relative vs drive-absolute paths. This merely describes the + // status quo, rather than being obviously right + [['c:'], 'c:.'], + [['c:.'], 'c:.'], + [['c:', ''], 'c:.'], + [['', 'c:'], 'c:.'], + [['c:.', '/'], 'c:./'], + [['c:.', 'file'], 'c:file'], + [['c:', '/'], 'c:/'], + [['c:', 'file'], 'c:/file'] + ]); +} + +// Run the join tests. +joinTests.forEach(function(test) { + var actual = path.join.apply(path, test[0]); + var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1]; + var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' + + '\n expect=' + JSON.stringify(expected) + + '\n actual=' + JSON.stringify(actual); + if (actual !== expected) failures.push('\n' + message); + // assert.equal(actual, expected, message); +}); +assert.equal(failures.length, 0, failures.join('')); +var joinThrowTests = [true, false, 7, null, {}, undefined, [], NaN]; +joinThrowTests.forEach(function(test) { + assert.throws(function() { + path.join(test); + }, TypeError); + assert.throws(function() { + path.resolve(test); + }, TypeError); +}); + + +// path normalize tests +assert.equal(path.win32.normalize('./fixtures///b/../b/c.js'), + 'fixtures\\b\\c.js'); +assert.equal(path.win32.normalize('/foo/../../../bar'), '\\bar'); +assert.equal(path.win32.normalize('a//b//../b'), 'a\\b'); +assert.equal(path.win32.normalize('a//b//./c'), 'a\\b\\c'); +assert.equal(path.win32.normalize('a//b//.'), 'a\\b'); +assert.equal(path.win32.normalize('//server/share/dir/file.ext'), + '\\\\server\\share\\dir\\file.ext'); + +assert.equal(path.posix.normalize('./fixtures///b/../b/c.js'), + 'fixtures/b/c.js'); +assert.equal(path.posix.normalize('/foo/../../../bar'), '/bar'); +assert.equal(path.posix.normalize('a//b//../b'), 'a/b'); +assert.equal(path.posix.normalize('a//b//./c'), 'a/b/c'); +assert.equal(path.posix.normalize('a//b//.'), 'a/b'); + +// path.resolve tests +if (isWindows) { + // windows + var resolveTests = + // arguments result + [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], + [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], + [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], + [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], + [['.'], process.cwd()], + [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], + [['c:/', '//'], 'c:\\'], + [['c:/', '//dir'], 'c:\\dir'], + [['c:/', '//server/share'], '\\\\server\\share\\'], + [['c:/', '//server//share'], '\\\\server\\share\\'], + [['c:/', '///some//dir'], 'c:\\some\\dir'] + ]; +} else { + // Posix + var resolveTests = + // arguments result + [[['/var/lib', '../', 'file/'], '/var/file'], + [['/var/lib', '/../', 'file/'], '/file'], + [['a/b/c/', '../../..'], process.cwd()], + [['.'], process.cwd()], + [['/some/dir', '.', '/absolute/'], '/absolute']]; +} +var failures = []; +resolveTests.forEach(function(test) { + var actual = path.resolve.apply(path, test[0]); + var expected = test[1]; + var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' + + '\n expect=' + JSON.stringify(expected) + + '\n actual=' + JSON.stringify(actual); + if (actual !== expected) failures.push('\n' + message); + // assert.equal(actual, expected, message); +}); +assert.equal(failures.length, 0, failures.join('')); + +// path.isAbsolute tests +assert.equal(path.win32.isAbsolute('//server/file'), true); +assert.equal(path.win32.isAbsolute('\\\\server\\file'), true); +assert.equal(path.win32.isAbsolute('C:/Users/'), true); +assert.equal(path.win32.isAbsolute('C:\\Users\\'), true); +assert.equal(path.win32.isAbsolute('C:cwd/another'), false); +assert.equal(path.win32.isAbsolute('C:cwd\\another'), false); +assert.equal(path.win32.isAbsolute('directory/directory'), false); +assert.equal(path.win32.isAbsolute('directory\\directory'), false); + +assert.equal(path.posix.isAbsolute('/home/foo'), true); +assert.equal(path.posix.isAbsolute('/home/foo/..'), true); +assert.equal(path.posix.isAbsolute('bar/'), false); +assert.equal(path.posix.isAbsolute('./baz'), false); + +// path.relative tests +if (isWindows) { + // windows + var relativeTests = + // arguments result + [['c:/blah\\blah', 'd:/games', 'd:\\games'], + ['c:/aaaa/bbbb', 'c:/aaaa', '..'], + ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], + ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], + ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], + ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], + ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], + ['c:/aaaa/bbbb', 'd:\\', 'd:\\']]; +} else { + // posix + var relativeTests = + // arguments result + [['/var/lib', '/var', '..'], + ['/var/lib', '/bin', '../../bin'], + ['/var/lib', '/var/lib', ''], + ['/var/lib', '/var/apache', '../apache'], + ['/var/', '/var/lib', 'lib'], + ['/', '/var/lib', 'var/lib']]; +} +var failures = []; +relativeTests.forEach(function(test) { + var actual = path.relative(test[0], test[1]); + var expected = test[2]; + var message = 'path.relative(' + + test.slice(0, 2).map(JSON.stringify).join(',') + + ')' + + '\n expect=' + JSON.stringify(expected) + + '\n actual=' + JSON.stringify(actual); + if (actual !== expected) failures.push('\n' + message); +}); +assert.equal(failures.length, 0, failures.join('')); + +// windows +assert.equal(path.win32.sep, '\\'); +// posix +assert.equal(path.posix.sep, '/'); + +// path.delimiter tests +// windows +assert.equal(path.win32.delimiter, ';'); + +// posix +assert.equal(path.posix.delimiter, ':'); + + +if (isWindows) + assert.deepEqual(path, path.win32, 'should be win32 path module'); +else + assert.deepEqual(path, path.posix, 'should be posix path module'); diff --git a/test/parallel/test-pipe-file-to-http.js b/test/parallel/test-pipe-file-to-http.js new file mode 100644 index 000000000..1b3ba7089 --- /dev/null +++ b/test/parallel/test-pipe-file-to-http.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var http = require('http'); +var path = require('path'); +var cp = require('child_process'); + +var filename = path.join(common.tmpDir || '/tmp', 'big'); +var clientReqComplete = false; +var count = 0; + +var server = http.createServer(function(req, res) { + console.error('SERVER request'); + var timeoutId; + assert.equal('POST', req.method); + req.pause(); + common.error('request paused'); + + setTimeout(function() { + req.resume(); + common.error('request resumed'); + }, 1000); + + req.on('data', function(chunk) { + common.error('recv data! nchars = ' + chunk.length); + count += chunk.length; + }); + + req.on('end', function() { + if (timeoutId) { + clearTimeout(timeoutId); + } + console.log('request complete from server'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(); + }); +}); +server.listen(common.PORT); + +server.on('listening', function() { + var cmd = common.ddCommand(filename, 10240); + console.log('dd command: ', cmd); + + cp.exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + console.error('EXEC returned successfully stdout=%d stderr=%d', + stdout.length, stderr.length); + makeRequest(); + }); +}); + +function makeRequest() { + var req = http.request({ + port: common.PORT, + path: '/', + method: 'POST' + }); + + common.error('pipe!'); + + var s = fs.ReadStream(filename); + s.pipe(req); + s.on('data', function(chunk) { + console.error('FS data chunk=%d', chunk.length); + }); + s.on('end', function() { + console.error('FS end'); + }); + s.on('close', function(err) { + if (err) throw err; + clientReqComplete = true; + common.error('client finished sending request'); + }); + + req.on('response', function(res) { + console.error('RESPONSE', res.statusCode, res.headers); + res.resume(); + res.on('end', function() { + console.error('RESPONSE end'); + server.close(); + }); + }); +} + +process.on('exit', function() { + assert.equal(1024 * 10240, count); + assert.ok(clientReqComplete); +}); diff --git a/test/parallel/test-pipe-return-val.js b/test/parallel/test-pipe-return-val.js new file mode 100644 index 000000000..274e9f5bc --- /dev/null +++ b/test/parallel/test-pipe-return-val.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This test ensures SourceStream.pipe(DestStream) returns DestStream + +var common = require('../common'); +var Stream = require('stream').Stream; +var assert = require('assert'); +var util = require('util'); + +var sourceStream = new Stream(); +var destStream = new Stream(); +var result = sourceStream.pipe(destStream); + +assert.strictEqual(result, destStream); + diff --git a/test/parallel/test-process-active-wraps.js b/test/parallel/test-process-active-wraps.js new file mode 100644 index 000000000..63fc218de --- /dev/null +++ b/test/parallel/test-process-active-wraps.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var net = require('net'); + +function expect(activeHandles, activeRequests) { + assert.equal(process._getActiveHandles().length, activeHandles); + assert.equal(process._getActiveRequests().length, activeRequests); +} + +var handles = []; + +(function() { + expect(0, 0); + var server = net.createServer().listen(common.PORT); + expect(1, 0); + server.close(); + expect(1, 0); // server handle doesn't shut down until next tick + handles.push(server); +})(); + +(function() { + expect(1, 0); + var conn = net.createConnection(common.PORT); + conn.on('error', function() { /* ignore */ }); + expect(2, 1); + conn.destroy(); + expect(2, 1); // client handle doesn't shut down until next tick + handles.push(conn); +})(); + +(function() { + var n = 0; + handles.forEach(function(handle) { + handle.once('close', onclose); + }); + function onclose() { + if (++n === handles.length) setImmediate(expect, 0, 0); + } +})(); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js new file mode 100644 index 000000000..0c38f6ac7 --- /dev/null +++ b/test/parallel/test-process-argv-0.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var util = require('util'); +var path = require('path'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var common = require('../common'); + +console.error('argv=%j', process.argv); +console.error('exec=%j', process.execPath); + +if (process.argv[2] !== "child") { + var child = spawn('./node', [__filename, "child"], { + cwd: path.dirname(process.execPath) + }); + + var childArgv0 = ''; + var childErr = ''; + child.stdout.on('data', function(chunk) { + childArgv0 += chunk; + }); + child.stderr.on('data', function(chunk) { + childErr += chunk; + }); + child.on('exit', function () { + console.error('CHILD: %s', childErr.trim().split('\n').join('\nCHILD: ')); + if (process.platform === 'win32') { + // On Windows argv[0] is not expanded into full path + assert.equal(childArgv0, './node'); + } else { + assert.equal(childArgv0, process.execPath); + } + }); +} +else { + process.stdout.write(process.argv[0]); +} diff --git a/test/parallel/test-process-before-exit.js b/test/parallel/test-process-before-exit.js new file mode 100644 index 000000000..261ac253c --- /dev/null +++ b/test/parallel/test-process-before-exit.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); + +var N = 5; +var n = 0; + +function f() { + if (++n < N) setTimeout(f, 5); +} +process.on('beforeExit', f); +process.on('exit', function() { + assert.equal(n, N + 1); // The sixth time we let it through. +}); diff --git a/test/parallel/test-process-binding.js b/test/parallel/test-process-binding.js new file mode 100644 index 000000000..c803a8083 --- /dev/null +++ b/test/parallel/test-process-binding.js @@ -0,0 +1,16 @@ +var assert = require('assert'); + +assert.throws( + function() { + process.binding('test'); + }, + /No such module: test/ +); + +assert.doesNotThrow(function () { + process.binding('buffer'); +}, function(err) { + if ( (err instanceof Error) ) { + return true; + } +}, "unexpected error"); diff --git a/test/parallel/test-process-config.js b/test/parallel/test-process-config.js new file mode 100644 index 000000000..b3236cd5e --- /dev/null +++ b/test/parallel/test-process-config.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); + +// check for existence +assert(process.hasOwnProperty('config')); + +// ensure that `process.config` is an Object +assert(Object(process.config) === process.config); + +var configPath = path.resolve(__dirname, '..', '..', 'config.gypi'); +var config = fs.readFileSync(configPath, 'utf8'); + +// clean up comment at the first line +config = config.split('\n').slice(1).join('\n').replace(/'/g, '"'); +config = JSON.parse(config, function(key, value) { + if (value === 'true') return true; + if (value === 'false') return false; + return value; +}); + +assert.deepEqual(config, process.config); diff --git a/test/parallel/test-process-env.js b/test/parallel/test-process-env.js new file mode 100644 index 000000000..919d0d54e --- /dev/null +++ b/test/parallel/test-process-env.js @@ -0,0 +1,79 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// first things first, set the timezone; see tzset(3) +process.env.TZ = 'Europe/Amsterdam'; + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +/* For the moment we are not going to support setting the timezone via the + * environment variables. The problem is that various V8 platform backends + * deal with timezone in different ways. The windows platform backend caches + * the timezone value while the Linux one hits libc for every query. + +https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-linux.cc#L339-345 +https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-win32.cc#L590-596 + + +// time difference between Greenwich and Amsterdam is +2 hours in the summer +date = new Date('Fri, 10 Sep 1982 03:15:00 GMT'); +assert.equal(3, date.getUTCHours()); +assert.equal(5, date.getHours()); +*/ + + +// changes in environment should be visible to child processes +if (process.argv[2] == 'you-are-the-child') { + // failed assertion results in process exiting with status code 1 + assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); + assert.equal(42, process.env.NODE_PROCESS_ENV); + assert.equal('asdf', process.env.hasOwnProperty); + var hasOwnProperty = Object.prototype.hasOwnProperty; + var has = hasOwnProperty.call(process.env, 'hasOwnProperty'); + assert.equal(true, has); + process.exit(0); +} else { + assert.equal(Object.prototype.hasOwnProperty, process.env.hasOwnProperty); + var has = process.env.hasOwnProperty('hasOwnProperty'); + assert.equal(false, has); + + process.env.hasOwnProperty = 'asdf'; + + process.env.NODE_PROCESS_ENV = 42; + assert.equal(42, process.env.NODE_PROCESS_ENV); + + process.env.NODE_PROCESS_ENV_DELETED = 42; + assert.equal(true, 'NODE_PROCESS_ENV_DELETED' in process.env); + + delete process.env.NODE_PROCESS_ENV_DELETED; + assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); + + var child = spawn(process.argv[0], [process.argv[1], 'you-are-the-child']); + child.stdout.on('data', function(data) { console.log(data.toString()); }); + child.stderr.on('data', function(data) { console.log(data.toString()); }); + child.on('exit', function(statusCode) { + if (statusCode != 0) { + process.exit(statusCode); // failed assertion in child process + } + }); +} diff --git a/test/parallel/test-process-exec-argv.js b/test/parallel/test-process-exec-argv.js new file mode 100644 index 000000000..395753b72 --- /dev/null +++ b/test/parallel/test-process-exec-argv.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var spawn = require('child_process').spawn; + +if (process.argv[2] === 'child') { + process.stdout.write(JSON.stringify(process.execArgv)); +} else { + var execArgv = ['--harmony_proxies', '--stack-size=256']; + var args = [__filename, 'child', 'arg0']; + var child = spawn(process.execPath, execArgv.concat(args)); + var out = ''; + + child.stdout.on('data', function (chunk) { + out += chunk; + }); + + child.on('exit', function () { + assert.deepEqual(JSON.parse(out), execArgv); + }); +} diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js new file mode 100644 index 000000000..2488175d3 --- /dev/null +++ b/test/parallel/test-process-exit-code.js @@ -0,0 +1,103 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +switch (process.argv[2]) { + case 'child1': + return child1(); + case 'child2': + return child2(); + case 'child3': + return child3(); + case 'child4': + return child4(); + case 'child5': + return child5(); + case undefined: + return parent(); + default: + throw new Error('wtf'); +} + +function child1() { + process.exitCode = 42; + process.on('exit', function(code) { + assert.equal(code, 42); + }); +} + +function child2() { + process.exitCode = 99; + process.on('exit', function(code) { + assert.equal(code, 42); + }); + process.exit(42); +} + +function child3() { + process.exitCode = 99; + process.on('exit', function(code) { + assert.equal(code, 0); + }); + process.exit(0); +} + +function child4() { + process.exitCode = 99; + process.on('exit', function(code) { + if (code !== 1) { + console.log('wrong code! expected 1 for uncaughtException'); + process.exit(99); + } + }); + throw new Error('ok'); +} + +function child5() { + process.exitCode = 95; + process.on('exit', function(code) { + assert.equal(code, 95); + process.exitCode = 99; + }); +} + +function parent() { + test('child1', 42); + test('child2', 42); + test('child3', 0); + test('child4', 1); + test('child5', 99); +} + +function test(arg, exit) { + var spawn = require('child_process').spawn; + var node = process.execPath; + var f = __filename; + var option = { stdio: [ 0, 1, 'ignore' ] }; + spawn(node, [f, arg], option).on('exit', function(code) { + assert.equal(code, exit, 'wrong exit for ' + + arg + '\nexpected:' + exit + + ' but got:' + code); + console.log('ok - %s exited with %d', arg, exit); + }); +} diff --git a/test/parallel/test-process-exit-from-before-exit.js b/test/parallel/test-process-exit-from-before-exit.js new file mode 100644 index 000000000..4818a6c19 --- /dev/null +++ b/test/parallel/test-process-exit-from-before-exit.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); + +process.on('beforeExit', common.mustCall(function() { + setTimeout(assert.fail, 5); + process.exit(0); // Should execute immediately even if we schedule new work. + assert.fail(); +})); diff --git a/test/parallel/test-process-exit-recursive.js b/test/parallel/test-process-exit-recursive.js new file mode 100644 index 000000000..ba5b5dc5b --- /dev/null +++ b/test/parallel/test-process-exit-recursive.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +// recursively calling .exit() should not overflow the call stack +var nexits = 0; + +process.on('exit', function(code) { + assert.equal(nexits++, 0); + assert.equal(code, 1); + + // now override the exit code of 1 with 0 so that the test passes + process.exit(0); +}); + +process.exit(1); diff --git a/test/parallel/test-process-exit.js b/test/parallel/test-process-exit.js new file mode 100644 index 000000000..365d5f109 --- /dev/null +++ b/test/parallel/test-process-exit.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// calling .exit() from within "exit" should not overflow the call stack +var nexits = 0; + +process.on('exit', function(code) { + assert.equal(nexits++, 0); + assert.equal(code, 0); + process.exit(); +}); + +// "exit" should be emitted unprovoked diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js new file mode 100644 index 000000000..16d017b3c --- /dev/null +++ b/test/parallel/test-process-getgroups.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +if (process.platform === 'darwin') { + console.log('Skipping. Output of `id -G` is unreliable on Darwin.'); + return; +} + +if (typeof process.getgroups === 'function') { + var groups = process.getgroups(); + assert(Array.isArray(groups)); + assert(groups.length > 0); + exec('id -G', function(err, stdout) { + if (err) throw err; + var real_groups = stdout.match(/\d+/g).map(Number); + assert.equal(groups.length, real_groups.length); + check(groups, real_groups); + check(real_groups, groups); + }); +} + +function check(a, b) { + for (var i = 0; i < a.length; ++i) assert(b.indexOf(a[i]) !== -1); +} diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js new file mode 100644 index 000000000..d8ffcafa9 --- /dev/null +++ b/test/parallel/test-process-hrtime.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// the default behavior, return an Array "tuple" of numbers +var tuple = process.hrtime(); + +// validate the default behavior +validateTuple(tuple); + +// validate that passing an existing tuple returns another valid tuple +validateTuple(process.hrtime(tuple)); + +// test that only an Array may be passed to process.hrtime() +assert.throws(function() { + process.hrtime(1); +}); + +function validateTuple(tuple) { + assert(Array.isArray(tuple)); + assert.equal(2, tuple.length); + tuple.forEach(function (v) { + assert.equal('number', typeof v); + assert(isFinite(v)); + }); +} diff --git a/test/parallel/test-process-kill-null.js b/test/parallel/test-process-kill-null.js new file mode 100644 index 000000000..520210ef1 --- /dev/null +++ b/test/parallel/test-process-kill-null.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var cat = spawn('cat'); +var called; + +assert.ok(process.kill(cat.pid, 0)); + +cat.on('exit', function() { + assert.throws(function() { + process.kill(cat.pid, 0); + }, Error); +}); + +cat.stdout.on('data', function() { + called = true; + process.kill(cat.pid, 'SIGKILL'); +}); + +// EPIPE when null sig fails +cat.stdin.write('test'); + +process.on('exit', function() { + assert.ok(called); +}); diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js new file mode 100644 index 000000000..6e4e7d83a --- /dev/null +++ b/test/parallel/test-process-kill-pid.js @@ -0,0 +1,88 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); + +// test variants of pid +// +// null: TypeError +// undefined: TypeError +// +// 'SIGTERM': TypeError +// +// String(process.pid): TypeError +// +// Nan, Infinity, -Infinity: TypeError +// +// 0, String(0): our group process +// +// process.pid, String(process.pid): ourself + +assert.throws(function() { process.kill('SIGTERM'); }, TypeError); +assert.throws(function() { process.kill(null); }, TypeError); +assert.throws(function() { process.kill(undefined); }, TypeError); +assert.throws(function() { process.kill(+'not a number'); }, TypeError); +assert.throws(function() { process.kill(1/0); }, TypeError); +assert.throws(function() { process.kill(-1/0); }, TypeError); + +// Test kill argument processing in valid cases. +// +// Monkey patch _kill so that we don't actually send any signals, particularly +// that we don't kill our process group, or try to actually send ANY signals on +// windows, which doesn't support them. +function kill(tryPid, trySig, expectPid, expectSig) { + var getPid; + var getSig; + var origKill = process._kill; + process._kill = function(pid, sig) { + getPid = pid; + getSig = sig; + + // un-monkey patch process._kill + process._kill = origKill; + }; + + process.kill(tryPid, trySig); + + assert.equal(getPid, expectPid); + assert.equal(getSig, expectSig); +} + +// Note that SIGHUP and SIGTERM map to 1 and 15 respectively, even on Windows +// (for Windows, libuv maps 1 and 15 to the correct behaviour). + +kill(0, 'SIGHUP', 0, 1); +kill(0, undefined, 0, 15); +kill('0', 'SIGHUP', 0, 1); +kill('0', undefined, 0, 15); + +// negative numbers are meaningful on unix +kill(-1, 'SIGHUP', -1, 1); +kill(-1, undefined, -1, 15); +kill('-1', 'SIGHUP', -1, 1); +kill('-1', undefined, -1, 15); + +kill(process.pid, 'SIGHUP', process.pid, 1); +kill(process.pid, undefined, process.pid, 15); +kill(String(process.pid), 'SIGHUP', process.pid, 1); +kill(String(process.pid), undefined, process.pid, 15); diff --git a/test/parallel/test-process-next-tick.js b/test/parallel/test-process-next-tick.js new file mode 100644 index 000000000..0322a033e --- /dev/null +++ b/test/parallel/test-process-next-tick.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var N = 2; +var tickCount = 0; +var exceptionCount = 0; + +function cb() { + ++tickCount; + throw new Error(); +} + +for (var i = 0; i < N; ++i) { + process.nextTick(cb); +} + +process.on('uncaughtException', function() { + ++exceptionCount; +}); + +process.on('exit', function() { + process.removeAllListeners('uncaughtException'); + assert.equal(tickCount, N); + assert.equal(exceptionCount, N); +}); diff --git a/test/parallel/test-process-raw-debug.js b/test/parallel/test-process-raw-debug.js new file mode 100644 index 000000000..3c14c9eb5 --- /dev/null +++ b/test/parallel/test-process-raw-debug.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var os = require('os'); + +switch (process.argv[2]) { + case 'child': + return child(); + case undefined: + return parent(); + default: + throw new Error('wtf? ' + process.argv[2]); +} + +function parent() { + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child']); + + var output = ''; + + child.stderr.on('data', function(c) { + output += c; + }); + + child.stderr.setEncoding('utf8'); + + child.stderr.on('end', function() { + assert.equal(output, 'I can still debug!' + os.EOL); + console.log('ok - got expected message'); + }); + + child.on('exit', function(c) { + assert(!c); + console.log('ok - child exited nicely'); + }); +} + +function child() { + // even when all hope is lost... + + process.nextTick = function() { + throw new Error('No ticking!'); + }; + + var stderr = process.stderr; + stderr.write = function() { + throw new Error('No writing to stderr!'); + }; + + process._rawDebug('I can still %s!', 'debug'); +} diff --git a/test/parallel/test-process-wrap.js b/test/parallel/test-process-wrap.js new file mode 100644 index 000000000..892b028e3 --- /dev/null +++ b/test/parallel/test-process-wrap.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var Process = process.binding('process_wrap').Process; +var Pipe = process.binding('pipe_wrap').Pipe; +var pipe = new Pipe(); +var p = new Process(); + +var processExited = false; +var gotPipeEOF = false; +var gotPipeData = false; + +p.onexit = function(exitCode, signal) { + console.log('exit'); + p.close(); + pipe.readStart(); + + assert.equal(0, exitCode); + assert.equal(0, signal); + + processExited = true; +}; + +pipe.onread = function(err, b, off, len) { + assert.ok(processExited); + if (b) { + gotPipeData = true; + console.log('read %d', len); + } else { + gotPipeEOF = true; + pipe.close(); + } +}; + +p.spawn({ + file: process.execPath, + args: [process.execPath, '-v'], + stdio: [ + { type: 'ignore' }, + { type: 'pipe', handle: pipe }, + { type: 'ignore' } + ] +}); + +// 'this' safety +// https://github.com/joyent/node/issues/6690 +assert.throws(function() { + var notp = { spawn: p.spawn }; + notp.spawn({ + file: process.execPath, + args: [process.execPath, '-v'], + stdio: [ + { type: 'ignore' }, + { type: 'pipe', handle: pipe }, + { type: 'ignore' } + ] + }); +}, TypeError); + +process.on('exit', function() { + assert.ok(processExited); + assert.ok(gotPipeEOF); + assert.ok(gotPipeData); +}); diff --git a/test/parallel/test-punycode.js b/test/parallel/test-punycode.js new file mode 100644 index 000000000..fa6a9c0ec --- /dev/null +++ b/test/parallel/test-punycode.js @@ -0,0 +1,195 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Copyright (C) 2011 by Ben Noordhuis +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +var common = require('../common'); +var punycode = require('punycode'); +var assert = require('assert'); + +assert.equal(punycode.encode('ü'), 'tda'); +assert.equal(punycode.encode('Goethe'), 'Goethe-'); +assert.equal(punycode.encode('Bücher'), 'Bcher-kva'); +assert.equal(punycode.encode( + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'), + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'); +assert.equal(punycode.encode('日本語'), 'wgv71a119e'); + +assert.equal(punycode.decode('tda'), 'ü'); +assert.equal(punycode.decode('Goethe-'), 'Goethe'); +assert.equal(punycode.decode('Bcher-kva'), 'Bücher'); +assert.equal(punycode.decode( + 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), + 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); +assert.equal(punycode.decode('wgv71a119e'), '日本語'); + +// http://tools.ietf.org/html/rfc3492#section-7.1 +var tests = { + // (A) Arabic (Egyptian) + 'egbpdaj6bu4bxfgehfvwxn': + '\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648' + + '\u0634\u0639\u0631\u0628\u064A\u061F', + + // (B) Chinese (simplified) + 'ihqwcrb4cv8a8dqg056pqjye': + '\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587', + + // (C) Chinese (traditional) + 'ihqwctvzc91f659drss3x8bo0yb': + '\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587', + + // (D) Czech: Proprostnemluvesky + 'Proprostnemluvesky-uyb24dma41a': + '\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074\u011B\u006E' + + '\u0065\u006D\u006C\u0075\u0076\u00ED\u010D\u0065\u0073\u006B\u0079', + + // (E) Hebrew + '4dbcagdahymbxekheh6e0a7fei0b': + '\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8\u05DC\u05D0' + + '\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2\u05D1\u05E8\u05D9\u05EA', + + // (F) Hindi (Devanagari) + 'i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd': + '\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D\u0926\u0940' + + '\u0915\u094D\u092F\u094B\u0902\u0928\u0939\u0940\u0902\u092C\u094B' + + '\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902', + + // (G) Japanese (kanji and hiragana) + 'n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa': + '\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092\u8A71\u3057' + + '\u3066\u304F\u308C\u306A\u3044\u306E\u304B', + + // (H) Korean (Hangul syllables) + '989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c': + '\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774\uD55C\uAD6D' + + '\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74\uC5BC\uB9C8\uB098\uC88B' + + '\uC744\uAE4C', + + // (I) Russian (Cyrillic) + /* XXX disabled, fails - possibly a bug in the RFC + 'b1abfaaepdrnnbgefbaDotcwatmq2g4l': + '\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438' + + '\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E' + + '\u0440\u0443\u0441\u0441\u043A\u0438', + */ + + // (J) Spanish: PorqunopuedensimplementehablarenEspaol + 'PorqunopuedensimplementehablarenEspaol-fmd56a': + '\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070\u0075\u0065' + + '\u0064\u0065\u006E\u0073\u0069\u006D\u0070\u006C\u0065\u006D\u0065' + + '\u006E\u0074\u0065\u0068\u0061\u0062\u006C\u0061\u0072\u0065\u006E' + + '\u0045\u0073\u0070\u0061\u00F1\u006F\u006C', + + // (K) Vietnamese: Tisaohkhngth + // chnitingVit + 'TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g': + '\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B\u0068\u00F4' + + '\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068\u1EC9\u006E\u00F3\u0069' + + '\u0074\u0069\u1EBF\u006E\u0067\u0056\u0069\u1EC7\u0074', + + // (L) 3B + '3B-ww4c5e180e575a65lsy2b': + '\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F', + + // (M) -with-SUPER-MONKEYS + '-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n': + '\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074\u0068\u002D' + + '\u0053\u0055\u0050\u0045\u0052\u002D\u004D\u004F\u004E\u004B\u0045' + + '\u0059\u0053', + + // (N) Hello-Another-Way- + 'Hello-Another-Way--fc4qua05auwb3674vfr0b': + '\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F\u0074\u0068' + + '\u0065\u0072\u002D\u0057\u0061\u0079\u002D\u305D\u308C\u305E\u308C' + + '\u306E\u5834\u6240', + + // (O) 2 + '2-u9tlzr9756bt3uc0v': + '\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032', + + // (P) MajiKoi5 + 'MajiKoi5-783gue6qz075azm5e': + '\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059\u308B\u0035' + + '\u79D2\u524D', + + // (Q) de + 'de-jg4avhby1noc0d': + '\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0', + + // (R) + 'd9juau41awczczp': + '\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067', + + // (S) -> $1.00 <- + '-> $1.00 <--': + '\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020\u003C\u002D' +}; + +var errors = 0; + +for (var encoded in tests) { + var decoded = tests[encoded]; + try { + assert.equal(punycode.encode(decoded), encoded); + } catch (e) { + console.error('FAIL: expected %j, got %j', e.expected, e.actual); + errors++; + } + try { + assert.equal(punycode.decode(encoded), decoded); + } catch (e) { + console.error('FAIL: expected %j, got %j', e.expected, e.actual); + errors++; + } +} + +// BMP code point +assert.equal(punycode.ucs2.encode([0x61]), 'a'); +// supplementary code point (surrogate pair) +assert.equal(punycode.ucs2.encode([0x1D306]), '\uD834\uDF06'); +// high surrogate +assert.equal(punycode.ucs2.encode([0xD800]), '\uD800'); +// high surrogate followed by non-surrogates +assert.equal(punycode.ucs2.encode([0xD800, 0x61, 0x62]), '\uD800ab'); +// low surrogate +assert.equal(punycode.ucs2.encode([0xDC00]), '\uDC00'); +// low surrogate followed by non-surrogates +assert.equal(punycode.ucs2.encode([0xDC00, 0x61, 0x62]), '\uDC00ab'); + +assert.equal(errors, 0); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js new file mode 100644 index 000000000..6bb3fe7c6 --- /dev/null +++ b/test/parallel/test-querystring.js @@ -0,0 +1,260 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// test using assert +var qs = require('querystring'); + +// folding block, commented to pass gjslint +// {{{ +// [ wonkyQS, canonicalQS, obj ] +var qsTestCases = [ + ['foo=918854443121279438895193', + 'foo=918854443121279438895193', + {'foo': '918854443121279438895193'}], + ['foo=bar', 'foo=bar', {'foo': 'bar'}], + ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], + ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], + ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', + 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', + {'my weird field': 'q1!2"\'w$5&7/z8)?' }], + ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], + ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], + ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', + { 'str': 'foo', + 'arr': ['1', '2', '3'], + 'somenull': '', + 'undef': ''}], + [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], + ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], + ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], + // See: https://github.com/joyent/node/issues/1707 + ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', + { hasOwnProperty: 'x', + toString: 'foo', + valueOf: 'bar', + __defineGetter__: 'baz' }], + // See: https://github.com/joyent/node/issues/3058 + ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }], + [null, '', {}], + [undefined, '', {}] +]; + +// [ wonkyQS, canonicalQS, obj ] +var qsColonTestCases = [ + ['foo:bar', 'foo:bar', {'foo': 'bar'}], + ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], + ['foo:1&bar:2;baz:quux', + 'foo:1%26bar%3A2;baz:quux', + {'foo': '1&bar:2', 'baz': 'quux'}], + ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], + ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] +]; + +// [wonkyObj, qs, canonicalObj] +var extendedFunction = function() {}; +extendedFunction.prototype = {a: 'b'}; +var qsWeirdObjects = [ + [{regexp: /./g}, 'regexp=', {'regexp': ''}], + [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], + [{fn: function() {}}, 'fn=', {'fn': ''}], + [{fn: new Function('')}, 'fn=', {'fn': ''}], + [{math: Math}, 'math=', {'math': ''}], + [{e: extendedFunction}, 'e=', {'e': ''}], + [{d: new Date()}, 'd=', {'d': ''}], + [{d: Date}, 'd=', {'d': ''}], + [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], + [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], + [{n: null}, 'n=', {'n': ''}], + [{nan: NaN}, 'nan=', {'nan': ''}], + [{inf: Infinity}, 'inf=', {'inf': ''}], + [{a: [], b: []}, '', {}] +]; +// }}} + +var vm = require('vm'); +var foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); + +var qsNoMungeTestCases = [ + ['', {}], + ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], + ['foo=bar&foo=baz', foreignObject], + ['blah=burp', {'blah': 'burp'}], + ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], + ['frappucino=muffin&goat%5B%5D=scone&pond=moose', + {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], + ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] +]; + +assert.strictEqual('918854443121279438895193', + qs.parse('id=918854443121279438895193').id); + +// test that the canonical qs is parsed properly. +qsTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0])); +}); + +// test that the colon test cases can do the same +qsColonTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':')); +}); + +// test the weird objects, that they get parsed properly +qsWeirdObjects.forEach(function(testCase) { + assert.deepEqual(testCase[2], qs.parse(testCase[1])); +}); + +qsNoMungeTestCases.forEach(function(testCase) { + assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=')); +}); + +// test the nested qs-in-qs case +(function() { + var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); + f.q = qs.parse(f.q); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); +})(); + +// nested in colon +(function() { + var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); + f.q = qs.parse(f.q, ';', ':'); + assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); +})(); + +// now test stringifying + +// basic +qsTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2])); +}); + +qsColonTestCases.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':')); +}); + +qsWeirdObjects.forEach(function(testCase) { + assert.equal(testCase[1], qs.stringify(testCase[0])); +}); + +// nested +var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }) +}); +assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz'); + +assert.doesNotThrow(function() { + qs.parse(undefined); +}); + +// nested in colon +var f = qs.stringify({ + a: 'b', + q: qs.stringify({ + x: 'y', + y: 'z' + }, ';', ':') +}, ';', ':'); +assert.equal(f, 'a:b;q:x%3Ay%3By%3Az'); + + +assert.deepEqual({}, qs.parse()); + + +// Test limiting +assert.equal( + Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length, + 1); + +// Test removing limit +function testUnlimitedKeys() { + var query = {}, + url; + + for (var i = 0; i < 2000; i++) query[i] = i; + + url = qs.stringify(query); + + assert.equal( + Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length, + 2000); +} +testUnlimitedKeys(); + + +var b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + + '%0d%ac%a2%2f%9d%eb%d8%a2%e6'); +// +assert.equal(0xd3, b[0]); +assert.equal(0xf2, b[1]); +assert.equal(0x55, b[2]); +assert.equal(0x67, b[3]); +assert.equal(0x1f, b[4]); +assert.equal(0x36, b[5]); +assert.equal(0x76, b[6]); +assert.equal(0x24, b[7]); +assert.equal(0x5e, b[8]); +assert.equal(0x98, b[9]); +assert.equal(0xcb, b[10]); +assert.equal(0x0d, b[11]); +assert.equal(0xac, b[12]); +assert.equal(0xa2, b[13]); +assert.equal(0x2f, b[14]); +assert.equal(0x9d, b[15]); +assert.equal(0xeb, b[16]); +assert.equal(0xd8, b[17]); +assert.equal(0xa2, b[18]); +assert.equal(0xe6, b[19]); + + +// Test custom decode +function demoDecode(str) { + return str + str; +} +assert.deepEqual( + qs.parse('a=a&b=b&c=c', null, null, { decodeURIComponent: demoDecode }), + { aa: 'aa', bb: 'bb', cc: 'cc' }); + + +// Test custom encode +function demoEncode(str) { + return str[0]; +} +var obj = { aa: 'aa', bb: 'bb', cc: 'cc' }; +assert.equal( + qs.stringify(obj, null, null, { encodeURIComponent: demoEncode }), + 'a=a&b=b&c=c'); + +// test overriding .unescape +var prevUnescape = qs.unescape; +qs.unescape = function (str) { + return str.replace(/o/g, '_'); +}; +assert.deepEqual(qs.parse('foo=bor'), {f__: 'b_r'}); +qs.unescape = prevUnescape; diff --git a/test/parallel/test-readdouble.js b/test/parallel/test-readdouble.js new file mode 100644 index 000000000..6749e5b20 --- /dev/null +++ b/test/parallel/test-readdouble.js @@ -0,0 +1,129 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're reading in doubles correctly + */ +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * Test (64 bit) double + */ +function test(clazz) { + var buffer = new clazz(8); + + buffer[0] = 0x55; + buffer[1] = 0x55; + buffer[2] = 0x55; + buffer[3] = 0x55; + buffer[4] = 0x55; + buffer[5] = 0x55; + buffer[6] = 0xd5; + buffer[7] = 0x3f; + ASSERT.equal(1.1945305291680097e+103, buffer.readDoubleBE(0)); + ASSERT.equal(0.3333333333333333, buffer.readDoubleLE(0)); + + buffer[0] = 1; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + buffer[4] = 0; + buffer[5] = 0; + buffer[6] = 0xf0; + buffer[7] = 0x3f; + ASSERT.equal(7.291122019655968e-304, buffer.readDoubleBE(0)); + ASSERT.equal(1.0000000000000002, buffer.readDoubleLE(0)); + + buffer[0] = 2; + ASSERT.equal(4.778309726801735e-299, buffer.readDoubleBE(0)); + ASSERT.equal(1.0000000000000004, buffer.readDoubleLE(0)); + + buffer[0] = 1; + buffer[6] = 0; + buffer[7] = 0; + ASSERT.equal(7.291122019556398e-304, buffer.readDoubleBE(0)); + ASSERT.equal(5e-324, buffer.readDoubleLE(0)); + + buffer[0] = 0xff; + buffer[1] = 0xff; + buffer[2] = 0xff; + buffer[3] = 0xff; + buffer[4] = 0xff; + buffer[5] = 0xff; + buffer[6] = 0x0f; + buffer[7] = 0x00; + ASSERT.ok(isNaN(buffer.readDoubleBE(0))); + ASSERT.equal(2.225073858507201e-308, buffer.readDoubleLE(0)); + + buffer[6] = 0xef; + buffer[7] = 0x7f; + ASSERT.ok(isNaN(buffer.readDoubleBE(0))); + ASSERT.equal(1.7976931348623157e+308, buffer.readDoubleLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + buffer[4] = 0; + buffer[5] = 0; + buffer[6] = 0xf0; + buffer[7] = 0x3f; + ASSERT.equal(3.03865e-319, buffer.readDoubleBE(0)); + ASSERT.equal(1, buffer.readDoubleLE(0)); + + buffer[6] = 0; + buffer[7] = 0x40; + ASSERT.equal(3.16e-322, buffer.readDoubleBE(0)); + ASSERT.equal(2, buffer.readDoubleLE(0)); + + buffer[7] = 0xc0; + ASSERT.equal(9.5e-322, buffer.readDoubleBE(0)); + ASSERT.equal(-2, buffer.readDoubleLE(0)); + + buffer[6] = 0x10; + buffer[7] = 0; + ASSERT.equal(2.0237e-320, buffer.readDoubleBE(0)); + ASSERT.equal(2.2250738585072014e-308, buffer.readDoubleLE(0)); + + buffer[6] = 0; + ASSERT.equal(0, buffer.readDoubleBE(0)); + ASSERT.equal(0, buffer.readDoubleLE(0)); + ASSERT.equal(false, 1 / buffer.readDoubleLE(0) < 0); + + buffer[7] = 0x80; + ASSERT.equal(6.3e-322, buffer.readDoubleBE(0)); + ASSERT.equal(0, buffer.readDoubleLE(0)); + ASSERT.equal(true, 1 / buffer.readDoubleLE(0) < 0); + + buffer[6] = 0xf0; + buffer[7] = 0x7f; + ASSERT.equal(3.0418e-319, buffer.readDoubleBE(0)); + ASSERT.equal(Infinity, buffer.readDoubleLE(0)); + + buffer[6] = 0xf0; + buffer[7] = 0xff; + ASSERT.equal(3.04814e-319, buffer.readDoubleBE(0)); + ASSERT.equal(-Infinity, buffer.readDoubleLE(0)); +} + + +test(Buffer); diff --git a/test/parallel/test-readfloat.js b/test/parallel/test-readfloat.js new file mode 100644 index 000000000..586b992c5 --- /dev/null +++ b/test/parallel/test-readfloat.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're reading in floats correctly + */ +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * Test (32 bit) float + */ +function test(clazz) { + var buffer = new clazz(4); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0x80; + buffer[3] = 0x3f; + ASSERT.equal(4.600602988224807e-41, buffer.readFloatBE(0)); + ASSERT.equal(1, buffer.readFloatLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0xc0; + ASSERT.equal(2.6904930515036488e-43, buffer.readFloatBE(0)); + ASSERT.equal(-2, buffer.readFloatLE(0)); + + buffer[0] = 0xff; + buffer[1] = 0xff; + buffer[2] = 0x7f; + buffer[3] = 0x7f; + ASSERT.ok(isNaN(buffer.readFloatBE(0))); + ASSERT.equal(3.4028234663852886e+38, buffer.readFloatLE(0)); + + buffer[0] = 0xab; + buffer[1] = 0xaa; + buffer[2] = 0xaa; + buffer[3] = 0x3e; + ASSERT.equal(-1.2126478207002966e-12, buffer.readFloatBE(0)); + ASSERT.equal(0.3333333432674408, buffer.readFloatLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0; + buffer[3] = 0; + ASSERT.equal(0, buffer.readFloatBE(0)); + ASSERT.equal(0, buffer.readFloatLE(0)); + ASSERT.equal(false, 1 / buffer.readFloatLE(0) < 0); + + buffer[3] = 0x80; + ASSERT.equal(1.793662034335766e-43, buffer.readFloatBE(0)); + ASSERT.equal(0, buffer.readFloatLE(0)); + ASSERT.equal(true, 1 / buffer.readFloatLE(0) < 0); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0x80; + buffer[3] = 0x7f; + ASSERT.equal(4.609571298396486e-41, buffer.readFloatBE(0)); + ASSERT.equal(Infinity, buffer.readFloatLE(0)); + + buffer[0] = 0; + buffer[1] = 0; + buffer[2] = 0x80; + buffer[3] = 0xff; + ASSERT.equal(4.627507918739843e-41, buffer.readFloatBE(0)); + ASSERT.equal(-Infinity, buffer.readFloatLE(0)); +} + + +test(Buffer); diff --git a/test/parallel/test-readint.js b/test/parallel/test-readint.js new file mode 100644 index 000000000..f1b79e816 --- /dev/null +++ b/test/parallel/test-readint.js @@ -0,0 +1,118 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're reading in signed integers correctly + */ +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * Test 8 bit signed integers + */ +function test8(clazz) { + var data = new clazz(4); + + data[0] = 0x23; + ASSERT.equal(0x23, data.readInt8(0)); + + data[0] = 0xff; + ASSERT.equal(-1, data.readInt8(0)); + + data[0] = 0x87; + data[1] = 0xab; + data[2] = 0x7c; + data[3] = 0xef; + ASSERT.equal(-121, data.readInt8(0)); + ASSERT.equal(-85, data.readInt8(1)); + ASSERT.equal(124, data.readInt8(2)); + ASSERT.equal(-17, data.readInt8(3)); +} + + +function test16(clazz) { + var buffer = new clazz(6); + + buffer[0] = 0x16; + buffer[1] = 0x79; + ASSERT.equal(0x1679, buffer.readInt16BE(0)); + ASSERT.equal(0x7916, buffer.readInt16LE(0)); + + buffer[0] = 0xff; + buffer[1] = 0x80; + ASSERT.equal(-128, buffer.readInt16BE(0)); + ASSERT.equal(-32513, buffer.readInt16LE(0)); + + /* test offset with weenix */ + buffer[0] = 0x77; + buffer[1] = 0x65; + buffer[2] = 0x65; + buffer[3] = 0x6e; + buffer[4] = 0x69; + buffer[5] = 0x78; + ASSERT.equal(0x7765, buffer.readInt16BE(0)); + ASSERT.equal(0x6565, buffer.readInt16BE(1)); + ASSERT.equal(0x656e, buffer.readInt16BE(2)); + ASSERT.equal(0x6e69, buffer.readInt16BE(3)); + ASSERT.equal(0x6978, buffer.readInt16BE(4)); + ASSERT.equal(0x6577, buffer.readInt16LE(0)); + ASSERT.equal(0x6565, buffer.readInt16LE(1)); + ASSERT.equal(0x6e65, buffer.readInt16LE(2)); + ASSERT.equal(0x696e, buffer.readInt16LE(3)); + ASSERT.equal(0x7869, buffer.readInt16LE(4)); +} + + +function test32(clazz) { + var buffer = new clazz(6); + + buffer[0] = 0x43; + buffer[1] = 0x53; + buffer[2] = 0x16; + buffer[3] = 0x79; + ASSERT.equal(0x43531679, buffer.readInt32BE(0)); + ASSERT.equal(0x79165343, buffer.readInt32LE(0)); + + buffer[0] = 0xff; + buffer[1] = 0xfe; + buffer[2] = 0xef; + buffer[3] = 0xfa; + ASSERT.equal(-69638, buffer.readInt32BE(0)); + ASSERT.equal(-84934913, buffer.readInt32LE(0)); + + buffer[0] = 0x42; + buffer[1] = 0xc3; + buffer[2] = 0x95; + buffer[3] = 0xa9; + buffer[4] = 0x36; + buffer[5] = 0x17; + ASSERT.equal(0x42c395a9, buffer.readInt32BE(0)); + ASSERT.equal(-1013601994, buffer.readInt32BE(1)); + ASSERT.equal(-1784072681, buffer.readInt32BE(2)); + ASSERT.equal(-1449802942, buffer.readInt32LE(0)); + ASSERT.equal(917083587, buffer.readInt32LE(1)); + ASSERT.equal(389458325, buffer.readInt32LE(2)); +} + + +test8(Buffer); +test16(Buffer); +test32(Buffer); diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js new file mode 100644 index 000000000..b86dd5a8a --- /dev/null +++ b/test/parallel/test-readline-interface.js @@ -0,0 +1,342 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var assert = require('assert'); +var readline = require('readline'); +var EventEmitter = require('events').EventEmitter; +var inherits = require('util').inherits; + +function FakeInput() { + EventEmitter.call(this); +} +inherits(FakeInput, EventEmitter); +FakeInput.prototype.resume = function() {}; +FakeInput.prototype.pause = function() {}; +FakeInput.prototype.write = function() {}; +FakeInput.prototype.end = function() {}; + +function isWarned(emitter) { + for (var name in emitter) { + var listeners = emitter[name]; + if (listeners.warned) return true; + } + return false; +} + +[ true, false ].forEach(function(terminal) { + var fi; + var rli; + var called; + + // sending a full line + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + called = false; + rli.on('line', function(line) { + called = true; + assert.equal(line, 'asdf'); + }); + fi.emit('data', 'asdf\n'); + assert.ok(called); + + // sending a blank line + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + called = false; + rli.on('line', function(line) { + called = true; + assert.equal(line, ''); + }); + fi.emit('data', '\n'); + assert.ok(called); + + // sending a single character with no newline + fi = new FakeInput(); + rli = new readline.Interface(fi, {}); + called = false; + rli.on('line', function(line) { + called = true; + }); + fi.emit('data', 'a'); + assert.ok(!called); + rli.close(); + + // sending a single character with no newline and then a newline + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + called = false; + rli.on('line', function(line) { + called = true; + assert.equal(line, 'a'); + }); + fi.emit('data', 'a'); + assert.ok(!called); + fi.emit('data', '\n'); + assert.ok(called); + rli.close(); + + // sending multiple newlines at once + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + var expectedLines = ['foo', 'bar', 'baz']; + var callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + fi.emit('data', expectedLines.join('\n') + '\n'); + assert.equal(callCount, expectedLines.length); + rli.close(); + + // sending multiple newlines at once that does not end with a new line + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + expectedLines = ['foo', 'bar', 'baz', 'bat']; + callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + fi.emit('data', expectedLines.join('\n')); + assert.equal(callCount, expectedLines.length - 1); + rli.close(); + + // sending multiple newlines at once that does not end with a new(empty) + // line and a `end` event + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + expectedLines = ['foo', 'bar', 'baz', '']; + callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + rli.on('close', function() { + callCount++; + }) + fi.emit('data', expectedLines.join('\n')); + fi.emit('end'); + assert.equal(callCount, expectedLines.length); + rli.close(); + + // sending multiple newlines at once that does not end with a new line + // and a `end` event(last line is) + + // \r\n should emit one line event, not two + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + expectedLines = ['foo', 'bar', 'baz', 'bat']; + callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + fi.emit('data', expectedLines.join('\r\n')); + assert.equal(callCount, expectedLines.length - 1); + rli.close(); + + // \r\n should emit one line event when split across multiple writes. + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + expectedLines = ['foo', 'bar', 'baz', 'bat']; + callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + expectedLines.forEach(function(line) { + fi.emit('data', line + '\r'); + fi.emit('data', '\n'); + }); + assert.equal(callCount, expectedLines.length); + rli.close(); + + // \r should behave like \n when alone + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: true }); + expectedLines = ['foo', 'bar', 'baz', 'bat']; + callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + fi.emit('data', expectedLines.join('\r')); + assert.equal(callCount, expectedLines.length - 1); + rli.close(); + + // \r at start of input should output blank line + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: true }); + expectedLines = ['', 'foo' ]; + callCount = 0; + rli.on('line', function(line) { + assert.equal(line, expectedLines[callCount]); + callCount++; + }); + fi.emit('data', '\rfoo\r'); + assert.equal(callCount, expectedLines.length); + rli.close(); + + // sending a multi-byte utf8 char over multiple writes + var buf = Buffer('☮', 'utf8'); + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + callCount = 0; + rli.on('line', function(line) { + callCount++; + assert.equal(line, buf.toString('utf8')); + }); + [].forEach.call(buf, function(i) { + fi.emit('data', Buffer([i])); + }); + assert.equal(callCount, 0); + fi.emit('data', '\n'); + assert.equal(callCount, 1); + rli.close(); + + // keypress + [ + ['a'], + ['\x1b'], + ['\x1b[31m'], + ['\x1b[31m', '\x1b[39m'], + ['\x1b[31m', 'a', '\x1b[39m', 'a'] + ].forEach(function (keypresses) { + fi = new FakeInput(); + callCount = 0; + var remainingKeypresses = keypresses.slice(); + function keypressListener (ch, key) { + callCount++; + if (ch) assert(!key.code); + assert.equal(key.sequence, remainingKeypresses.shift()); + }; + readline.emitKeypressEvents(fi); + fi.on('keypress', keypressListener); + fi.emit('data', keypresses.join('')); + assert.equal(callCount, keypresses.length); + assert.equal(remainingKeypresses.length, 0); + fi.removeListener('keypress', keypressListener); + fi.emit('data', ''); // removes listener + }); + + if (terminal) { + // question + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + expectedLines = ['foo']; + rli.question(expectedLines[0], function() { + rli.close(); + }); + var cursorPos = rli._getCursorPos(); + assert.equal(cursorPos.rows, 0); + assert.equal(cursorPos.cols, expectedLines[0].length); + rli.close(); + + // sending a multi-line question + fi = new FakeInput(); + rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); + expectedLines = ['foo', 'bar']; + rli.question(expectedLines.join('\n'), function() { + rli.close(); + }); + var cursorPos = rli._getCursorPos(); + assert.equal(cursorPos.rows, expectedLines.length - 1); + assert.equal(cursorPos.cols, expectedLines.slice(-1)[0].length); + rli.close(); + } + + // wide characters should be treated as two columns. + assert.equal(readline.isFullWidthCodePoint('a'.charCodeAt(0)), false); + assert.equal(readline.isFullWidthCodePoint('あ'.charCodeAt(0)), true); + assert.equal(readline.isFullWidthCodePoint('谢'.charCodeAt(0)), true); + assert.equal(readline.isFullWidthCodePoint('고'.charCodeAt(0)), true); + assert.equal(readline.isFullWidthCodePoint(0x1f251), true); // surrogate + assert.equal(readline.codePointAt('ABC', 0), 0x41); + assert.equal(readline.codePointAt('あいう', 1), 0x3044); + assert.equal(readline.codePointAt('\ud800\udc00', 0), // surrogate + 0x10000); + assert.equal(readline.codePointAt('\ud800\udc00A', 2), // surrogate + 0x41); + assert.equal(readline.getStringWidth('abcde'), 5); + assert.equal(readline.getStringWidth('古池や'), 6); + assert.equal(readline.getStringWidth('ノード.js'), 9); + assert.equal(readline.getStringWidth('你好'), 4); + assert.equal(readline.getStringWidth('안녕하세요'), 10); + assert.equal(readline.getStringWidth('A\ud83c\ude00BC'), 5); // surrogate + + // check if vt control chars are stripped + assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> '); + assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > '); + assert.equal(readline.stripVTControlCharacters('\u001b[31m\u001b[39m'), ''); + assert.equal(readline.stripVTControlCharacters('> '), '> '); + assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m'), 2); + assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m> '), 4); + assert.equal(readline.getStringWidth('\u001b[31m\u001b[39m'), 0); + assert.equal(readline.getStringWidth('> '), 2); + + assert.deepEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); + + // check EventEmitter memory leak + for (var i=0; i<12; i++) { + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + rl.close(); + assert.equal(isWarned(process.stdin._events), false); + assert.equal(isWarned(process.stdout._events), false); + } + + //can create a new readline Interface with a null output arugument + fi = new FakeInput(); + rli = new readline.Interface({input: fi, output: null, terminal: terminal }); + + called = false; + rli.on('line', function(line) { + called = true; + assert.equal(line, 'asdf'); + }); + fi.emit('data', 'asdf\n'); + assert.ok(called); + + assert.doesNotThrow(function() { + rli.setPrompt("ddd> "); + }); + + assert.doesNotThrow(function() { + rli.prompt(); + }); + + assert.doesNotThrow(function() { + rli.write('really shouldnt be seeing this'); + }); + + assert.doesNotThrow(function() { + rli.question("What do you think of node.js? ", function(answer) { + console.log("Thank you for your valuable feedback:", answer); + rli.close(); + }) + }); + +}); + diff --git a/test/parallel/test-readline-set-raw-mode.js b/test/parallel/test-readline-set-raw-mode.js new file mode 100644 index 000000000..f43443857 --- /dev/null +++ b/test/parallel/test-readline-set-raw-mode.js @@ -0,0 +1,90 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var assert = require('assert'); +var readline = require('readline'); +var Stream = require('stream'); + +var stream = new Stream(); +var expectedRawMode = true; +var rawModeCalled = false; +var resumeCalled = false; +var pauseCalled = false; + +stream.setRawMode = function(mode) { + rawModeCalled = true; + assert.equal(mode, expectedRawMode); +}; +stream.resume = function() { + resumeCalled = true; +}; +stream.pause = function() { + pauseCalled = true; +}; + +// when the "readline" starts in "terminal" mode, +// then setRawMode(true) should be called +var rli = readline.createInterface({ + input: stream, + output: stream, + terminal: true +}); +assert(rli.terminal); +assert(rawModeCalled); +assert(resumeCalled); +assert(!pauseCalled); + + +// pause() should call *not* call setRawMode() +rawModeCalled = false; +resumeCalled = false; +pauseCalled = false; +rli.pause(); +assert(!rawModeCalled); +assert(!resumeCalled); +assert(pauseCalled); + + +// resume() should *not* call setRawMode() +rawModeCalled = false; +resumeCalled = false; +pauseCalled = false; +rli.resume(); +assert(!rawModeCalled); +assert(resumeCalled); +assert(!pauseCalled); + + +// close() should call setRawMode(false) +expectedRawMode = false; +rawModeCalled = false; +resumeCalled = false; +pauseCalled = false; +rli.close(); +assert(rawModeCalled); +assert(!resumeCalled); +assert(pauseCalled); + +assert.deepEqual(stream.listeners('keypress'), []); +// one data listener for the keypress events. +assert.equal(stream.listeners('data').length, 1); diff --git a/test/parallel/test-readuint.js b/test/parallel/test-readuint.js new file mode 100644 index 000000000..2b11a61c9 --- /dev/null +++ b/test/parallel/test-readuint.js @@ -0,0 +1,109 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * A battery of tests to help us read a series of uints + */ + +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * We need to check the following things: + * - We are correctly resolving big endian (doesn't mean anything for 8 bit) + * - Correctly resolving little endian (doesn't mean anything for 8 bit) + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test8(clazz) { + var data = new clazz(4); + + data[0] = 23; + data[1] = 23; + data[2] = 23; + data[3] = 23; + ASSERT.equal(23, data.readUInt8(0)); + ASSERT.equal(23, data.readUInt8(1)); + ASSERT.equal(23, data.readUInt8(2)); + ASSERT.equal(23, data.readUInt8(3)); + + data[0] = 255; /* If it became a signed int, would be -1 */ + ASSERT.equal(255, data.readUInt8(0)); +} + + +/* + * Test 16 bit unsigned integers. We need to verify the same set as 8 bit, only + * now some of the issues actually matter: + * - We are correctly resolving big endian + * - Correctly resolving little endian + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test16(clazz) { + var data = new clazz(4); + + data[0] = 0; + data[1] = 0x23; + data[2] = 0x42; + data[3] = 0x3f; + ASSERT.equal(0x23, data.readUInt16BE(0)); + ASSERT.equal(0x2342, data.readUInt16BE(1)); + ASSERT.equal(0x423f, data.readUInt16BE(2)); + ASSERT.equal(0x2300, data.readUInt16LE(0)); + ASSERT.equal(0x4223, data.readUInt16LE(1)); + ASSERT.equal(0x3f42, data.readUInt16LE(2)); + + data[0] = 0xfe; + data[1] = 0xfe; + ASSERT.equal(0xfefe, data.readUInt16BE(0)); + ASSERT.equal(0xfefe, data.readUInt16LE(0)); +} + + +/* + * Test 32 bit unsigned integers. We need to verify the same set as 8 bit, only + * now some of the issues actually matter: + * - We are correctly resolving big endian + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test32(clazz) { + var data = new clazz(8); + + data[0] = 0x32; + data[1] = 0x65; + data[2] = 0x42; + data[3] = 0x56; + data[4] = 0x23; + data[5] = 0xff; + ASSERT.equal(0x32654256, data.readUInt32BE(0)); + ASSERT.equal(0x65425623, data.readUInt32BE(1)); + ASSERT.equal(0x425623ff, data.readUInt32BE(2)); + ASSERT.equal(0x56426532, data.readUInt32LE(0)); + ASSERT.equal(0x23564265, data.readUInt32LE(1)); + ASSERT.equal(0xff235642, data.readUInt32LE(2)); +} + + +test8(Buffer); +test16(Buffer); +test32(Buffer); diff --git a/test/parallel/test-regress-GH-4256.js b/test/parallel/test-regress-GH-4256.js new file mode 100644 index 000000000..9f937cc09 --- /dev/null +++ b/test/parallel/test-regress-GH-4256.js @@ -0,0 +1,25 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +process.domain = null; +timer = setTimeout(function() { + console.log("this console.log statement should not make node crash"); +}, 1); diff --git a/test/parallel/test-regress-GH-5927.js b/test/parallel/test-regress-GH-5927.js new file mode 100644 index 000000000..5f8f27661 --- /dev/null +++ b/test/parallel/test-regress-GH-5927.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var readline = require('readline'); + +var rl = readline.createInterface(process.stdin, process.stdout); +rl.resume(); + +var hasPaused = false; + +var origPause = rl.pause; +rl.pause = function() { + hasPaused = true; + origPause.apply(this, arguments); +} + +var origSetRawMode = rl._setRawMode; +rl._setRawMode = function(mode) { + assert.ok(hasPaused); + origSetRawMode.apply(this, arguments); +} + +rl.close(); diff --git a/test/parallel/test-regress-GH-6235.js b/test/parallel/test-regress-GH-6235.js new file mode 100644 index 000000000..e830f7bbe --- /dev/null +++ b/test/parallel/test-regress-GH-6235.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +assert.doesNotThrow(function() { + require('vm').runInNewContext('"use strict"; var v = 1; v = 2'); +}); diff --git a/test/parallel/test-regress-GH-7511.js b/test/parallel/test-regress-GH-7511.js new file mode 100644 index 000000000..9694f0499 --- /dev/null +++ b/test/parallel/test-regress-GH-7511.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + vm = require('vm'); + +assert.doesNotThrow(function() { + var context = vm.createContext({ process: process }); + var result = vm.runInContext('process.env["PATH"]', context); + assert.notEqual(undefined, result); +}); diff --git a/test/parallel/test-regress-GH-897.js b/test/parallel/test-regress-GH-897.js new file mode 100644 index 000000000..dd4399f16 --- /dev/null +++ b/test/parallel/test-regress-GH-897.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var t = Date.now(); +var diff; +setTimeout(function() { + diff = Date.now() - t; + console.error(diff); +}, 0.1); + + +process.on('exit', function() { + assert.ok(diff < 100); +}); diff --git a/test/parallel/test-regression-object-prototype.js b/test/parallel/test-regression-object-prototype.js new file mode 100644 index 000000000..158532ad8 --- /dev/null +++ b/test/parallel/test-regression-object-prototype.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +//console.log('puts before'); + +Object.prototype.xadsadsdasasdxx = function() { +}; + +console.log('puts after'); diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js new file mode 100644 index 000000000..fdbf18fa0 --- /dev/null +++ b/test/parallel/test-repl-.save.load.js @@ -0,0 +1,98 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var util = require('util'); +var join = require('path').join; +var fs = require('fs'); +var common = require('../common'); + +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function(data) { + var self = this; + data.forEach(function(line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; + +var works = [['inner.one'], 'inner.o']; + +var putIn = new ArrayStream(); +var testMe = repl.start('', putIn); + + +var testFile = [ + 'var top = function () {', + 'var inner = {one:1};' +]; +var saveFileName = join(common.tmpDir, 'test.save.js'); + +// input some data +putIn.run(testFile); + +// save it to a file +putIn.run(['.save ' + saveFileName]); + +// the file should have what I wrote +assert.equal(fs.readFileSync(saveFileName, 'utf8'), testFile.join('\n') + '\n'); + +// make sure that the REPL data is "correct" +// so when I load it back I know I'm good +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +// clear the REPL +putIn.run(['.clear']); + +// Load the file back in +putIn.run(['.load ' + saveFileName]); + +// make sure that the REPL data is "correct" +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +// clear the REPL +putIn.run(['.clear']); + +var loadFile = join(common.tmpDir, 'file.does.not.exist'); + +// should not break +putIn.write = function(data) { + // make sure I get a failed to load message and not some crazy error + assert.equal(data, 'Failed to load:' + loadFile + '\n'); + // eat me to avoid work + putIn.write = function() {}; +}; +putIn.run(['.load ' + loadFile]); + + +//TODO how do I do a failed .save test? diff --git a/test/parallel/test-repl-autolibs.js b/test/parallel/test-repl-autolibs.js new file mode 100644 index 000000000..b6f929471 --- /dev/null +++ b/test/parallel/test-repl-autolibs.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var util = require('util'); +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function (data) { + var self = this; + data.forEach(function (line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function () {}; +ArrayStream.prototype.write = function () {}; + +var putIn = new ArrayStream; +var testMe = repl.start('', putIn, null, true); + +test1(); + +function test1(){ + var gotWrite = false; + putIn.write = function (data) { + gotWrite = true; + if (data.length) { + + // inspect output matches repl output + assert.equal(data, util.inspect(require('fs'), null, 2, false) + '\n'); + // globally added lib matches required lib + assert.equal(global.fs, require('fs')); + test2(); + } + }; + assert(!gotWrite); + putIn.run(['fs']); + assert(gotWrite); +} + +function test2(){ + var gotWrite = false; + putIn.write = function(data) { + gotWrite = true; + if (data.length) { + // repl response error message + assert.equal(data, '{}\n'); + // original value wasn't overwritten + assert.equal(val, global.url); + } + }; + var val = {}; + global.url = val; + assert(!gotWrite); + putIn.run(['url']); + assert(gotWrite); +} diff --git a/test/parallel/test-repl-console.js b/test/parallel/test-repl-console.js new file mode 100644 index 000000000..3dca14b7f --- /dev/null +++ b/test/parallel/test-repl-console.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + Stream = require('stream'), + repl = require('repl'); + +// create a dummy stream that does nothing +var stream = new Stream(); +stream.write = stream.pause = stream.resume = function(){}; +stream.readable = stream.writable = true; + +var r = repl.start({ + input: stream, + output: stream, + useGlobal: false +}); + + +// ensure that the repl context gets its own "console" instance +assert(r.context.console); + +// ensure that the repl console instance is not the global one +assert.notStrictEqual(r.context.console, console); diff --git a/test/parallel/test-repl-domain.js b/test/parallel/test-repl-domain.js new file mode 100644 index 000000000..55b7dc475 --- /dev/null +++ b/test/parallel/test-repl-domain.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common.js'); + +var util = require('util'); +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function(data) { + var self = this; + data.forEach(function(line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; + +var putIn = new ArrayStream(); +var testMe = repl.start('', putIn); + +putIn.write = function(data) { + // Don't use assert for this because the domain might catch it, and + // give a false negative. Don't throw, just print and exit. + if (data === 'OK\n') { + console.log('ok'); + } + else { + console.error(data); + process.exit(1); + } +}; + +putIn.run([ + 'require("domain").create().on("error", function () { console.log("OK") })' + + '.run(function () { throw new Error("threw") })' +]); diff --git a/test/parallel/test-repl-end-emits-exit.js b/test/parallel/test-repl-end-emits-exit.js new file mode 100644 index 000000000..46eca2efb --- /dev/null +++ b/test/parallel/test-repl-end-emits-exit.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + Stream = require('stream'), + repl = require('repl'), + terminalExit = 0, + regularExit = 0; + +// create a dummy stream that does nothing +var stream = new Stream(); +stream.write = stream.pause = stream.resume = function(){}; +stream.readable = stream.writable = true; + +function testTerminalMode() { + var r1 = repl.start({ + input: stream, + output: stream, + terminal: true + }); + + process.nextTick(function() { + // manually fire a ^D keypress + stream.emit('data', '\u0004'); + }); + + r1.on('exit', function() { + // should be fired from the simulated ^D keypress + terminalExit++; + testRegularMode(); + }); +} + +function testRegularMode() { + var r2 = repl.start({ + input: stream, + output: stream, + terminal: false + }); + + process.nextTick(function() { + stream.emit('end'); + }); + + r2.on('exit', function() { + // should be fired from the simulated 'end' event + regularExit++; + }); +} + +process.on('exit', function() { + assert.equal(terminalExit, 1); + assert.equal(regularExit, 1); +}); + + +// start +testTerminalMode(); diff --git a/test/parallel/test-repl-harmony.js b/test/parallel/test-repl-harmony.js new file mode 100644 index 000000000..701dd5ed6 --- /dev/null +++ b/test/parallel/test-repl-harmony.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; +var args = ['--harmony', '--use-strict', '-i']; +var child = spawn(process.execPath, args); + +var input = 'function x(){const y=1;y=2}\n'; +var expectOut = /^> SyntaxError: Assignment to constant variable.\n/; + +child.stderr.setEncoding('utf8'); +child.stderr.on('data', function(c) { + throw new Error('child.stderr be silent'); +}); + +child.stdout.setEncoding('utf8'); +var out = ''; +child.stdout.on('data', function(c) { + out += c; +}); +child.stdout.on('end', function() { + assert(expectOut.test(out)); + console.log('ok'); +}); + +child.stdin.end(input); diff --git a/test/parallel/test-repl-options.js b/test/parallel/test-repl-options.js new file mode 100644 index 000000000..94a622da2 --- /dev/null +++ b/test/parallel/test-repl-options.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + Stream = require('stream'), + repl = require('repl'); + +common.globalCheck = false; + +// create a dummy stream that does nothing +var stream = new Stream(); +stream.write = stream.pause = stream.resume = function(){}; +stream.readable = stream.writable = true; + +// 1, mostly defaults +var r1 = repl.start({ + input: stream, + output: stream, + terminal: true +}); + +assert.equal(r1.input, stream); +assert.equal(r1.output, stream); +assert.equal(r1.input, r1.inputStream); +assert.equal(r1.output, r1.outputStream); +assert.equal(r1.terminal, true); +assert.equal(r1.useColors, r1.terminal); +assert.equal(r1.useGlobal, false); +assert.equal(r1.ignoreUndefined, false); + +// test r1 for backwards compact +assert.equal(r1.rli.input, stream); +assert.equal(r1.rli.output, stream); +assert.equal(r1.rli.input, r1.inputStream); +assert.equal(r1.rli.output, r1.outputStream); +assert.equal(r1.rli.terminal, true); +assert.equal(r1.useColors, r1.rli.terminal); + +// 2 +function writer() {} +function evaler() {} +var r2 = repl.start({ + input: stream, + output: stream, + terminal: false, + useColors: true, + useGlobal: true, + ignoreUndefined: true, + eval: evaler, + writer: writer +}); +assert.equal(r2.input, stream); +assert.equal(r2.output, stream); +assert.equal(r2.input, r2.inputStream); +assert.equal(r2.output, r2.outputStream); +assert.equal(r2.terminal, false); +assert.equal(r2.useColors, true); +assert.equal(r2.useGlobal, true); +assert.equal(r2.ignoreUndefined, true); +assert.equal(r2.writer, writer); + +// test r2 for backwards compact +assert.equal(r2.rli.input, stream); +assert.equal(r2.rli.output, stream); +assert.equal(r2.rli.input, r2.inputStream); +assert.equal(r2.rli.output, r2.outputStream); +assert.equal(r2.rli.terminal, false); + diff --git a/test/parallel/test-repl-require-cache.js b/test/parallel/test-repl-require-cache.js new file mode 100644 index 000000000..fe5753d21 --- /dev/null +++ b/test/parallel/test-repl-require-cache.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + repl = require('repl'); + +// https://github.com/joyent/node/issues/3226 + +require.cache.something = 1; +assert.equal(require.cache.something, 1); + +repl.start({ useGlobal: false }).close(); + +assert.equal(require.cache.something, 1); diff --git a/test/parallel/test-repl-reset-event.js b/test/parallel/test-repl-reset-event.js new file mode 100644 index 000000000..3554d17b9 --- /dev/null +++ b/test/parallel/test-repl-reset-event.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +common.globalCheck = false; + +var assert = require('assert'); +var repl = require('repl'); +var Stream = require('stream'); + +// create a dummy stream that does nothing +var dummy = new Stream(); +dummy.write = dummy.pause = dummy.resume = function(){}; +dummy.readable = dummy.writable = true; + +function testReset(cb) { + var r = repl.start({ + input: dummy, + output: dummy, + useGlobal: false + }); + r.context.foo = 42; + r.on('reset', function(context) { + assert(!!context, 'REPL did not emit a context with reset event'); + assert.equal(context, r.context, 'REPL emitted incorrect context'); + assert.equal(context.foo, undefined, 'REPL emitted the previous context, and is not using global as context'); + context.foo = 42; + cb(); + }); + r.resetContext(); +} + +function testResetGlobal(cb) { + var r = repl.start({ + input: dummy, + output: dummy, + useGlobal: true + }); + r.context.foo = 42; + r.on('reset', function(context) { + assert.equal(context.foo, 42, '"foo" property is missing from REPL using global as context'); + cb(); + }); + r.resetContext(); +} + +var timeout = setTimeout(function() { + assert.fail('Timeout, REPL did not emit reset events'); +}, 5000); + +testReset(function() { + testResetGlobal(function() { + clearTimeout(timeout); + }); +}); diff --git a/test/parallel/test-repl-setprompt.js b/test/parallel/test-repl-setprompt.js new file mode 100644 index 000000000..e5021c235 --- /dev/null +++ b/test/parallel/test-repl-setprompt.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'), + assert = require('assert'), + spawn = require('child_process').spawn, + os = require('os'), + util = require('util'); + +var args = [ + '-e', + 'var e = new (require("repl")).REPLServer("foo.. "); e.context.e = e;', +]; + +var p = "bar.. "; + +var child = spawn(process.execPath, args); + +child.stdout.setEncoding('utf8'); + +var data = ''; +child.stdout.on('data', function(d) { data += d }); + +child.stdin.end(util.format("e.setPrompt('%s');%s", p, os.EOL)); + +child.on('close', function(code, signal) { + assert.strictEqual(code, 0); + assert.ok(!signal); + var lines = data.split(/\n/); + assert.strictEqual(lines.pop(), p); +}); diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js new file mode 100644 index 000000000..74328f449 --- /dev/null +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +switch (process.argv[2]) { + case 'child': + return child(); + case undefined: + return parent(); + default: + throw new Error('wtf'); +} + +function parent() { + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child']); + + child.stderr.setEncoding('utf8'); + child.stderr.on('data', function(c) { + console.error('%j', c); + throw new Error('should not get stderr data'); + }); + + child.stdout.setEncoding('utf8'); + var out = ''; + child.stdout.on('data', function(c) { + out += c; + }); + child.stdout.on('end', function() { + assert.equal(out, '10\n'); + console.log('ok - got expected output'); + }); + + child.on('exit', function(c) { + assert(!c); + console.log('ok - exit success'); + }); +} + +function child() { + var vm = require('vm'); + try { + vm.runInThisContext('haf!@##&$!@$*!@', { displayErrors: false }); + } catch (er) { + var caught = true; + } + assert(caught); + vm.runInThisContext('console.log(10)', { displayErrors: false }); +} diff --git a/test/parallel/test-repl-tab-complete.js b/test/parallel/test-repl-tab-complete.js new file mode 100644 index 000000000..48df4033d --- /dev/null +++ b/test/parallel/test-repl-tab-complete.js @@ -0,0 +1,228 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +var repl = require('repl'); + +// A stream to push an array into a REPL +function ArrayStream() { + this.run = function(data) { + var self = this; + data.forEach(function(line) { + self.emit('data', line + '\n'); + }); + } +} +util.inherits(ArrayStream, require('stream').Stream); +ArrayStream.prototype.readable = true; +ArrayStream.prototype.writable = true; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; + +var works = [['inner.one'], 'inner.o']; +var doesNotBreak = [[], 'inner.o']; + +var putIn = new ArrayStream(); +var testMe = repl.start('', putIn); + +// Tab Complete will not break in an object literal +putIn.run(['.clear']); +putIn.run([ + 'var inner = {', + 'one:1' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); +testMe.complete('console.lo', function(error, data) { + assert.deepEqual(data, [['console.log'], 'console.lo']); +}); + +// Tab Complete will return globaly scoped variables +putIn.run(['};']); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// Tab Complete will not break in an ternary operator with () +putIn.run([ + 'var inner = ( true ' , + '?', + '{one: 1} : ' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a simple local variable +putIn.run([ + 'var top = function () {', + 'var inner = {one:1};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +// When you close the function scope tab complete will not return the +// locally scoped variable +putIn.run(['};']); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a complex local variable +putIn.run([ + 'var top = function () {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a complex local variable even if the function +// has parameters +putIn.run([ + 'var top = function (one, two) {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// Tab Complete will return a complex local variable even if the +// scope is nested inside an immediately executed function +putIn.run([ + 'var top = function () {', + '(function test () {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, works); +}); + +putIn.run(['.clear']); + +// currently does not work, but should not break note the inner function +// def has the params and { on a separate line +putIn.run([ + 'var top = function () {', + 'r = function test (', + ' one, two) {', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// currently does not work, but should not break, not the { +putIn.run([ + 'var top = function () {', + 'r = function test ()', + '{', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// currently does not work, but should not break +putIn.run([ + 'var top = function () {', + 'r = function test (', + ')', + '{', + 'var inner = {', + ' one:1', + '};' +]); +testMe.complete('inner.o', function(error, data) { + assert.deepEqual(data, doesNotBreak); +}); + +putIn.run(['.clear']); + +// make sure tab completion works on non-Objects +putIn.run([ + 'var str = "test";' +]); +testMe.complete('str.len', function(error, data) { + assert.deepEqual(data, [['str.length'], 'str.len']); +}); + +putIn.run(['.clear']); + +// tab completion should not break on spaces +var spaceTimeout = setTimeout(function() { + throw new Error('timeout'); +}, 1000); + +testMe.complete(' ', function(error, data) { + assert.deepEqual(data, [[],undefined]); + clearTimeout(spaceTimeout); +}); + +// tab completion should pick up the global "toString" object, and +// any other properties up the "global" object's prototype chain +testMe.complete('toSt', function(error, data) { + assert.deepEqual(data, [['toString'], 'toSt']); +}); + +// Tab complete provides built in libs for require() +putIn.run(['.clear']); + +testMe.complete('require(\'', function(error, data) { + assert.strictEqual(error, null); + repl._builtinLibs.forEach(function(lib) { + assert.notStrictEqual(data[0].indexOf(lib), -1, lib + ' not found'); + }); +}); + +testMe.complete('require(\'n', function(error, data) { + assert.strictEqual(error, null); + assert.deepEqual(data, [['net'], 'n']); +}); diff --git a/test/parallel/test-repl-timeout-throw.js b/test/parallel/test-repl-timeout-throw.js new file mode 100644 index 000000000..28f370909 --- /dev/null +++ b/test/parallel/test-repl-timeout-throw.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common.js'); + +var spawn = require('child_process').spawn; + +var child = spawn(process.execPath, [ '-i' ], { + stdio: [null, null, 2] +}); + +var stdout = ''; +child.stdout.setEncoding('utf8'); +child.stdout.on('data', function(c) { + process.stdout.write(c); + stdout += c; +}); + +child.stdin.write = function(original) { return function(c) { + process.stderr.write(c); + return original.call(child.stdin, c); +}}(child.stdin.write); + +child.stdout.once('data', function() { + child.stdin.write('var throws = 0;'); + child.stdin.write('process.on("exit",function(){console.log(throws)});'); + child.stdin.write('function thrower(){console.log("THROW",throws++);XXX};'); + child.stdin.write('setTimeout(thrower);""\n'); + + setTimeout(fsTest, 50); + function fsTest() { + var f = JSON.stringify(__filename); + child.stdin.write('fs.readFile(' + f + ', thrower);\n'); + setTimeout(eeTest, 50); + } + + function eeTest() { + child.stdin.write('setTimeout(function() {\n' + + ' var events = require("events");\n' + + ' var e = new events.EventEmitter;\n' + + ' process.nextTick(function() {\n' + + ' e.on("x", thrower);\n' + + ' setTimeout(function() {\n' + + ' e.emit("x");\n' + + ' });\n' + + ' });\n' + + '});"";\n'); + + setTimeout(child.stdin.end.bind(child.stdin), 200); + } +}); + +child.on('close', function(c) { + assert(!c); + // make sure we got 3 throws, in the end. + var lastLine = stdout.trim().split(/\r?\n/).pop(); + assert.equal(lastLine, '> 3'); +}); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js new file mode 100644 index 000000000..69b9b54d1 --- /dev/null +++ b/test/parallel/test-repl.js @@ -0,0 +1,344 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +common.globalCheck = false; + +var net = require('net'), + repl = require('repl'), + message = 'Read, Eval, Print Loop', + prompt_unix = 'node via Unix socket> ', + prompt_tcp = 'node via TCP socket> ', + prompt_multiline = '... ', + prompt_npm = 'npm should be run outside of the ' + + 'node repl, in your normal shell.\n' + + '(Press Control-D to exit.)\n', + expect_npm = prompt_npm + prompt_unix, + server_tcp, server_unix, client_tcp, client_unix, timer; + + +// absolute path to test/fixtures/a.js +var moduleFilename = require('path').join(common.fixturesDir, 'a'); + +console.error('repl test'); + +// function for REPL to run +invoke_me = function(arg) { + return 'invoked ' + arg; +}; + +function send_expect(list) { + if (list.length > 0) { + var cur = list.shift(); + + console.error('sending ' + JSON.stringify(cur.send)); + + cur.client.expect = cur.expect; + cur.client.list = list; + if (cur.send.length > 0) { + cur.client.write(cur.send + '\n'); + } + } +} + +function clean_up() { + client_tcp.end(); + client_unix.end(); + clearTimeout(timer); +} + +function error_test() { + // The other stuff is done so reuse unix socket + var read_buffer = ''; + client_unix.removeAllListeners('data'); + + client_unix.on('data', function(data) { + read_buffer += data.toString('ascii', 0, data.length); + console.error('Unix data: ' + JSON.stringify(read_buffer) + ', expecting ' + + (client_unix.expect.exec ? + client_unix.expect : + JSON.stringify(client_unix.expect))); + + if (read_buffer.indexOf(prompt_unix) !== -1) { + // if it's an exact match, then don't do the regexp + if (read_buffer !== client_unix.expect) { + var expect = client_unix.expect; + if (expect === prompt_multiline) + expect = /[\.]{3} /; + assert.ok(read_buffer.match(expect)); + console.error('match'); + } + read_buffer = ''; + if (client_unix.list && client_unix.list.length > 0) { + send_expect(client_unix.list); + } else { + console.error('End of Error test, running TCP test.'); + tcp_test(); + } + + } else if (read_buffer.indexOf(prompt_multiline) !== -1) { + // Check that you meant to send a multiline test + assert.strictEqual(prompt_multiline, client_unix.expect); + read_buffer = ''; + if (client_unix.list && client_unix.list.length > 0) { + send_expect(client_unix.list); + } else { + console.error('End of Error test, running TCP test.\n'); + tcp_test(); + } + + } else { + console.error('didn\'t see prompt yet, buffering.'); + } + }); + + send_expect([ + // Uncaught error throws and prints out + { client: client_unix, send: 'throw new Error(\'test error\');', + expect: /^Error: test error/ }, + // Common syntax error is treated as multiline command + { client: client_unix, send: 'function test_func() {', + expect: prompt_multiline }, + // You can recover with the .break command + { client: client_unix, send: '.break', + expect: prompt_unix }, + // But passing the same string to eval() should throw + { client: client_unix, send: 'eval("function test_func() {")', + expect: /^SyntaxError: Unexpected end of input/ }, + // Floating point numbers are not interpreted as REPL commands. + { client: client_unix, send: '.1234', + expect: '0.1234' }, + // Floating point expressions are not interpreted as REPL commands + { client: client_unix, send: '.1+.1', + expect: '0.2' }, + // Can parse valid JSON + { client: client_unix, send: 'JSON.parse(\'{"valid": "json"}\');', + expect: '{ valid: \'json\' }'}, + // invalid input to JSON.parse error is special case of syntax error, + // should throw + { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', + expect: /^SyntaxError: Unexpected token i/ }, + // end of input to JSON.parse error is special case of syntax error, + // should throw + { client: client_unix, send: 'JSON.parse(\'066\');', + expect: /^SyntaxError: Unexpected number/ }, + // should throw + { client: client_unix, send: 'JSON.parse(\'{\');', + expect: /^SyntaxError: Unexpected end of input/ }, + // invalid RegExps are a special case of syntax error, + // should throw + { client: client_unix, send: '/(/;', + expect: /^SyntaxError: Invalid regular expression\:/ }, + // invalid RegExp modifiers are a special case of syntax error, + // should throw (GH-4012) + { client: client_unix, send: 'new RegExp("foo", "wrong modifier");', + expect: /^SyntaxError: Invalid flags supplied to RegExp constructor/ }, + // strict mode syntax errors should be caught (GH-5178) + { client: client_unix, send: '(function() { "use strict"; return 0755; })()', + expect: /^SyntaxError: Octal literals are not allowed in strict mode/ }, + { client: client_unix, send: '(function() { "use strict"; return { p: 1, p: 2 }; })()', + expect: /^SyntaxError: Duplicate data property in object literal not allowed in strict mode/ }, + { client: client_unix, send: '(function(a, a, b) { "use strict"; return a + b + c; })()', + expect: /^SyntaxError: Strict mode function may not have duplicate parameter names/ }, + { client: client_unix, send: '(function() { "use strict"; with (this) {} })()', + expect: /^SyntaxError: Strict mode code may not include a with statement/ }, + { client: client_unix, send: '(function() { "use strict"; var x; delete x; })()', + expect: /^SyntaxError: Delete of an unqualified identifier in strict mode/ }, + { client: client_unix, send: '(function() { "use strict"; eval = 17; })()', + expect: /^SyntaxError: Unexpected eval or arguments in strict mode/ }, + { client: client_unix, send: '(function() { "use strict"; if (true){ function f() { } } })()', + expect: /^SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function/ }, + // Named functions can be used: + { client: client_unix, send: 'function blah() { return 1; }', + expect: prompt_unix }, + { client: client_unix, send: 'blah()', + expect: '1\n' + prompt_unix }, + // Functions should not evaluate twice (#2773) + { client: client_unix, send: 'var I = [1,2,3,function() {}]; I.pop()', + expect: '[Function]' }, + // Multiline object + { client: client_unix, send: '{ a: ', + expect: prompt_multiline }, + { client: client_unix, send: '1 }', + expect: '{ a: 1 }' }, + // Multiline anonymous function with comment + { client: client_unix, send: '(function () {', + expect: prompt_multiline }, + { client: client_unix, send: '// blah', + expect: prompt_multiline }, + { client: client_unix, send: 'return 1;', + expect: prompt_multiline }, + { client: client_unix, send: '})()', + expect: '1' }, + // npm prompt error message + { client: client_unix, send: 'npm install foobar', + expect: expect_npm }, + { client: client_unix, send: '(function () {\n\nreturn 1;\n})()', + expect: '1' }, + { client: client_unix, send: '{\n\na: 1\n}', + expect: '{ a: 1 }' }, + { client: client_unix, send: 'url.format("http://google.com")', + expect: 'http://google.com/' }, + { client: client_unix, send: 'var path = 42; path', + expect: '42' } + ]); +} + +function tcp_test() { + server_tcp = net.createServer(function(socket) { + assert.strictEqual(server_tcp, socket.server); + + socket.on('end', function() { + socket.end(); + }); + + repl.start(prompt_tcp, socket); + }); + + server_tcp.listen(common.PORT, function() { + var read_buffer = ''; + + client_tcp = net.createConnection(common.PORT); + + client_tcp.on('connect', function() { + assert.equal(true, client_tcp.readable); + assert.equal(true, client_tcp.writable); + + send_expect([ + { client: client_tcp, send: '', + expect: prompt_tcp }, + { client: client_tcp, send: 'invoke_me(333)', + expect: ('\'' + 'invoked 333' + '\'\n' + prompt_tcp) }, + { client: client_tcp, send: 'a += 1', + expect: ('12346' + '\n' + prompt_tcp) }, + { client: client_tcp, + send: 'require(' + JSON.stringify(moduleFilename) + ').number', + expect: ('42' + '\n' + prompt_tcp) } + ]); + }); + + client_tcp.on('data', function(data) { + read_buffer += data.toString('ascii', 0, data.length); + console.error('TCP data: ' + JSON.stringify(read_buffer) + + ', expecting ' + JSON.stringify(client_tcp.expect)); + if (read_buffer.indexOf(prompt_tcp) !== -1) { + assert.strictEqual(client_tcp.expect, read_buffer); + console.error('match'); + read_buffer = ''; + if (client_tcp.list && client_tcp.list.length > 0) { + send_expect(client_tcp.list); + } else { + console.error('End of TCP test.\n'); + clean_up(); + } + } else { + console.error('didn\'t see prompt yet, buffering'); + } + }); + + client_tcp.on('error', function(e) { + throw e; + }); + + client_tcp.on('close', function() { + server_tcp.close(); + }); + }); + +} + +function unix_test() { + server_unix = net.createServer(function(socket) { + assert.strictEqual(server_unix, socket.server); + + socket.on('end', function() { + socket.end(); + }); + + repl.start({ + prompt: prompt_unix, + input: socket, + output: socket, + useGlobal: true + }).context.message = message; + }); + + server_unix.on('listening', function() { + var read_buffer = ''; + + client_unix = net.createConnection(common.PIPE); + + client_unix.on('connect', function() { + assert.equal(true, client_unix.readable); + assert.equal(true, client_unix.writable); + + send_expect([ + { client: client_unix, send: '', + expect: prompt_unix }, + { client: client_unix, send: 'message', + expect: ('\'' + message + '\'\n' + prompt_unix) }, + { client: client_unix, send: 'invoke_me(987)', + expect: ('\'' + 'invoked 987' + '\'\n' + prompt_unix) }, + { client: client_unix, send: 'a = 12345', + expect: ('12345' + '\n' + prompt_unix) }, + { client: client_unix, send: '{a:1}', + expect: ('{ a: 1 }' + '\n' + prompt_unix) } + ]); + }); + + client_unix.on('data', function(data) { + read_buffer += data.toString('ascii', 0, data.length); + console.error('Unix data: ' + JSON.stringify(read_buffer) + + ', expecting ' + JSON.stringify(client_unix.expect)); + if (read_buffer.indexOf(prompt_unix) !== -1) { + assert.strictEqual(client_unix.expect, read_buffer); + console.error('match'); + read_buffer = ''; + if (client_unix.list && client_unix.list.length > 0) { + send_expect(client_unix.list); + } else { + console.error('End of Unix test, running Error test.\n'); + process.nextTick(error_test); + } + } else { + console.error('didn\'t see prompt yet, buffering.'); + } + }); + + client_unix.on('error', function(e) { + throw e; + }); + + client_unix.on('close', function() { + server_unix.close(); + }); + }); + + server_unix.listen(common.PIPE); +} + +unix_test(); + +timer = setTimeout(function() { + assert.fail('Timeout'); +}, 5000); diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js new file mode 100644 index 000000000..2f812044a --- /dev/null +++ b/test/parallel/test-require-cache.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +(function testInjectFakeModule() { + var relativePath = '../fixtures/semicolon'; + var absolutePath = require.resolve(relativePath); + var fakeModule = {}; + + require.cache[absolutePath] = {exports: fakeModule}; + + assert.strictEqual(require(relativePath), fakeModule); +})(); + + +(function testInjectFakeNativeModule() { + var relativePath = 'fs'; + var fakeModule = {}; + + require.cache[relativePath] = {exports: fakeModule}; + + assert.strictEqual(require(relativePath), fakeModule); +})(); diff --git a/test/parallel/test-require-exceptions.js b/test/parallel/test-require-exceptions.js new file mode 100644 index 000000000..307e3e2f3 --- /dev/null +++ b/test/parallel/test-require-exceptions.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// A module with an error in it should throw +assert.throws(function() { + require(common.fixturesDir + '/throws_error'); +}); + +// Requiring the same module again should throw as well +assert.throws(function() { + require(common.fixturesDir + '/throws_error'); +}); + +// Requiring a module that does not exist should throw an +// error with its `code` set to MODULE_NOT_FOUND +assert.throws(function() { + require(common.fixturesDir + '/DOES_NOT_EXIST'); +}, function(e) { + assert.equal('MODULE_NOT_FOUND', e.code); + return true; +}); diff --git a/test/parallel/test-require-extensions-main.js b/test/parallel/test-require-extensions-main.js new file mode 100644 index 000000000..032f2eb2c --- /dev/null +++ b/test/parallel/test-require-extensions-main.js @@ -0,0 +1,4 @@ +var common = require('../common'); +var assert = require('assert'); + +require(common.fixturesDir + '/require-bin/bin/req.js'); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js new file mode 100644 index 000000000..6469d14ff --- /dev/null +++ b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var content = require(common.fixturesDir + + '/json-with-directory-name-module/module-stub/one-trailing-slash/two/three.js'); + +assert.notEqual(content.rocko, 'artischocko'); +assert.equal(content, 'hello from module-stub!'); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir.js b/test/parallel/test-require-extensions-same-filename-as-dir.js new file mode 100644 index 000000000..fbfba3b9b --- /dev/null +++ b/test/parallel/test-require-extensions-same-filename-as-dir.js @@ -0,0 +1,29 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var content = require(common.fixturesDir + + '/json-with-directory-name-module/module-stub/one/two/three.js'); + +assert.notEqual(content.rocko, 'artischocko'); +assert.equal(content, 'hello from module-stub!'); diff --git a/test/parallel/test-require-json.js b/test/parallel/test-require-json.js new file mode 100644 index 000000000..59b1e3d61 --- /dev/null +++ b/test/parallel/test-require-json.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +try { + require('../fixtures/invalid.json'); +} catch (err) { + var re = /test[\/\\]fixtures[\/\\]invalid.json: Unexpected string/; + var i = err.message.match(re); + assert(null !== i, 'require() json error should include path'); +} diff --git a/test/parallel/test-require-resolve.js b/test/parallel/test-require-resolve.js new file mode 100644 index 000000000..490deae68 --- /dev/null +++ b/test/parallel/test-require-resolve.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var fixturesDir = common.fixturesDir; +var assert = require('assert'); +var path = require('path'); + +assert.equal( + path.join(__dirname, '../fixtures/a.js').toLowerCase(), + require.resolve('../fixtures/a').toLowerCase()); +assert.equal( + path.join(fixturesDir, 'a.js').toLowerCase(), + require.resolve(path.join(fixturesDir, 'a')).toLowerCase()); +assert.equal( + path.join(fixturesDir, 'nested-index', 'one', 'index.js').toLowerCase(), + require.resolve('../fixtures/nested-index/one').toLowerCase()); +assert.equal('path', require.resolve('path')); + +console.log('ok'); diff --git a/test/parallel/test-signal-handler.js b/test/parallel/test-signal-handler.js new file mode 100644 index 000000000..5531e2f55 --- /dev/null +++ b/test/parallel/test-signal-handler.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// SIGUSR1 and SIGHUP are not supported on Windows +if (process.platform === 'win32') { + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +console.log('process.pid: ' + process.pid); + +var first = 0, + second = 0; + +var sighup = false; + +process.on('SIGUSR1', function() { + console.log('Interrupted by SIGUSR1'); + first += 1; +}); + +process.on('SIGUSR1', function() { + second += 1; + setTimeout(function() { + console.log('End.'); + process.exit(0); + }, 5); +}); + +var i = 0; +setInterval(function() { + console.log('running process...' + ++i); + + if (i == 5) { + process.kill(process.pid, 'SIGUSR1'); + } +}, 1); + +// Test on condition where a watcher for SIGNAL +// has been previously registered, and `process.listeners(SIGNAL).length === 1` +process.on('SIGHUP', function() {}); +process.removeAllListeners('SIGHUP'); +process.on('SIGHUP', function() { sighup = true }); +process.kill(process.pid, 'SIGHUP'); + +process.on('exit', function() { + assert.equal(1, first); + assert.equal(1, second); + assert.equal(true, sighup); +}); diff --git a/test/parallel/test-signal-safety.js b/test/parallel/test-signal-safety.js new file mode 100644 index 000000000..4707b634d --- /dev/null +++ b/test/parallel/test-signal-safety.js @@ -0,0 +1,11 @@ +var common = require('../common.js'); +var assert = require('assert'); +var Signal = process.binding('signal_wrap').Signal; + +// Test Signal `this` safety +// https://github.com/joyent/node/issues/6690 +assert.throws(function() { + var s = new Signal(); + var nots = { start: s.start }; + nots.start(9); +}, TypeError); diff --git a/test/parallel/test-smalloc.js b/test/parallel/test-smalloc.js new file mode 100644 index 000000000..198b5c7f5 --- /dev/null +++ b/test/parallel/test-smalloc.js @@ -0,0 +1,332 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var os = require('os'); + +// first grab js api's +var smalloc = require('smalloc'); +var alloc = smalloc.alloc; +var dispose = smalloc.dispose; +var copyOnto = smalloc.copyOnto; +var kMaxLength = smalloc.kMaxLength; +var Types = smalloc.Types; +// sliceOnto is volatile and cannot be exposed to users. +var sliceOnto = process.binding('smalloc').sliceOnto; + + +// verify allocation + +var b = alloc(5, {}); +assert.ok(typeof b === 'object'); +for (var i = 0; i < 5; i++) + assert.ok(b[i] !== undefined); + + +var b = {}; +var c = alloc(5, b); +assert.equal(b, c); +assert.deepEqual(b, c); + + +var b = alloc(5, {}); +var c = {}; +c._data = sliceOnto(b, c, 0, 5); +assert.ok(typeof c._data === 'object'); +assert.equal(b, c._data); +assert.deepEqual(b, c._data); + + +// verify writes + +var b = alloc(5, {}); +for (var i = 0; i < 5; i++) + b[i] = i; +for (var i = 0; i < 5; i++) + assert.equal(b[i], i); + + +var b = alloc(1, Types.Uint8); +b[0] = 256; +assert.equal(b[0], 0); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Int8); +b[0] = 128; +assert.equal(b[0], -128); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Uint16); +b[0] = 65536; +assert.equal(b[0], 0); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Int16); +b[0] = 32768; +assert.equal(b[0], -32768); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Uint32); +b[0] = 4294967296; +assert.equal(b[0], 0); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Int32); +b[0] = 2147483648; +assert.equal(b[0], -2147483648); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Float); +b[0] = 0.1111111111111111; +assert.equal(b[0], 0.1111111119389534); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Double); +b[0] = 0.1111111111111111; +assert.equal(b[0], 0.1111111111111111); +assert.equal(b[1], undefined); + + +var b = alloc(1, Types.Uint8Clamped); +b[0] = 300; +assert.equal(b[0], 255); +assert.equal(b[1], undefined); + + +var b = alloc(6, {}); +var c0 = {}; +var c1 = {}; +c0._data = sliceOnto(b, c0, 0, 3); +c1._data = sliceOnto(b, c1, 3, 6); +for (var i = 0; i < 3; i++) { + c0[i] = i; + c1[i] = i + 3; +} +for (var i = 0; i < 3; i++) + assert.equal(b[i], i); +for (var i = 3; i < 6; i++) + assert.equal(b[i], i); + + +var a = alloc(6, {}); +var b = alloc(6, {}); +var c = alloc(12, {}); +for (var i = 0; i < 6; i++) { + a[i] = i; + b[i] = i * 2; +} +copyOnto(a, 0, c, 0, 6); +copyOnto(b, 0, c, 6, 6); +for (var i = 0; i < 6; i++) { + assert.equal(c[i], i); + assert.equal(c[i + 6], i * 2); +} + + +var b = alloc(1, Types.Double); +var c = alloc(2, Types.Uint32); +if (os.endianness() === 'LE') { + c[0] = 2576980378; + c[1] = 1069128089; +} else { + c[0] = 1069128089; + c[1] = 2576980378; +} +copyOnto(c, 0, b, 0, 2); +assert.equal(b[0], 0.1); + +var b = alloc(1, Types.Uint16); +var c = alloc(2, Types.Uint8); +c[0] = c[1] = 0xff; +copyOnto(c, 0, b, 0, 2); +assert.equal(b[0], 0xffff); + +var b = alloc(2, Types.Uint8); +var c = alloc(1, Types.Uint16); +c[0] = 0xffff; +copyOnto(c, 0, b, 0, 1); +assert.equal(b[0], 0xff); +assert.equal(b[1], 0xff); + + + +// verify checking external if has external memory + +// check objects +var b = {}; +assert.ok(!smalloc.hasExternalData(b)); +alloc(1, b); +assert.ok(smalloc.hasExternalData(b)); +var f = function() { }; +alloc(1, f); +assert.ok(smalloc.hasExternalData(f)); + +// and non-objects +assert.ok(!smalloc.hasExternalData(true)); +assert.ok(!smalloc.hasExternalData(1)); +assert.ok(!smalloc.hasExternalData('string')); +assert.ok(!smalloc.hasExternalData(null)); +assert.ok(!smalloc.hasExternalData()); + + +// verify alloc throws properly + +// arrays are not supported +assert.throws(function() { + alloc(0, []); +}, TypeError); + + +// no allocations larger than kMaxLength +assert.throws(function() { + alloc(kMaxLength + 1); +}, RangeError); + + +// properly convert to uint32 before checking overflow +assert.throws(function() { + alloc(-1); +}, RangeError); + + +// no allocating on what's been allocated +assert.throws(function() { + alloc(1, alloc(1)); +}, TypeError); + + +// throw for values passed that are not objects +assert.throws(function() { + alloc(1, 'a'); +}, TypeError); +assert.throws(function() { + alloc(1, true); +}, TypeError); +assert.throws(function() { + alloc(1, null); +}, TypeError); + + +// should not throw allocating to most objects +alloc(1, function() { }); +alloc(1, /abc/); +alloc(1, new Date()); + + +// range check on external array enumeration +assert.throws(function() { + alloc(1, 0); +}, TypeError); +assert.throws(function() { + alloc(1, 10); +}, TypeError); + +// very copyOnto throws properly + +// source must have data +assert.throws(function() { + copyOnto({}, 0, alloc(1), 0, 0); +}, Error); + + +// dest must have data +assert.throws(function() { + copyOnto(alloc(1), 0, {}, 0, 0); +}, Error); + + +// copyLength <= sourceLength +assert.throws(function() { + copyOnto(alloc(1), 0, alloc(3), 0, 2); +}, RangeError); + + +// copyLength <= destLength +assert.throws(function() { + copyOnto(alloc(3), 0, alloc(1), 0, 2); +}, RangeError); + + +// sourceStart <= sourceLength +assert.throws(function() { + copyOnto(alloc(1), 3, alloc(1), 0, 1); +}, RangeError); + + +// destStart <= destLength +assert.throws(function() { + copyOnto(alloc(1), 0, alloc(1), 3, 1); +}, RangeError); + + +// sourceStart + copyLength <= sourceLength +assert.throws(function() { + copyOnto(alloc(3), 1, alloc(3), 0, 3); +}, RangeError); + + +// destStart + copyLength <= destLength +assert.throws(function() { + copyOnto(alloc(3), 0, alloc(3), 1, 3); +}, RangeError); + + +// copy_length * array_size <= dest_length +assert.throws(function() { + copyOnto(alloc(2, Types.Double), 0, alloc(2, Types.Uint32), 0, 2); +}, RangeError); + + +// test disposal +var b = alloc(5, {}); +dispose(b); +for (var i = 0; i < 5; i++) + assert.equal(b[i], undefined); + + +// verify dispose throws properly + +// only allow object to be passed to dispose +assert.throws(function() { + smalloc.dispose(null); +}); + + +// can't dispose a Buffer +assert.throws(function() { + smalloc.dispose(new Buffer()); +}); + +assert.throws(function() { + smalloc.dispose(new Uint8Array(new ArrayBuffer(1))); +}); + +assert.throws(function() { + smalloc.dispose({}); +}); diff --git a/test/parallel/test-stdin-hang.js b/test/parallel/test-stdin-hang.js new file mode 100644 index 000000000..1edbf8c25 --- /dev/null +++ b/test/parallel/test-stdin-hang.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +// This test *only* verifies that invoking the stdin getter does not +// cause node to hang indefinitely. +// If it does, then the test-runner will nuke it. + +// invoke the getter. +process.stdin; + +console.error('Should exit normally now.'); diff --git a/test/parallel/test-stdin-pause-resume-sync.js b/test/parallel/test-stdin-pause-resume-sync.js new file mode 100644 index 000000000..0e202a306 --- /dev/null +++ b/test/parallel/test-stdin-pause-resume-sync.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +console.error('before opening stdin'); +process.stdin.resume(); +console.error('stdin opened'); +console.error('pausing stdin'); +process.stdin.pause(); +console.error('opening again'); +process.stdin.resume(); +console.error('pausing again'); +process.stdin.pause(); +console.error('should exit now'); diff --git a/test/parallel/test-stdin-pause-resume.js b/test/parallel/test-stdin-pause-resume.js new file mode 100644 index 000000000..fed5d6653 --- /dev/null +++ b/test/parallel/test-stdin-pause-resume.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +console.error('before opening stdin'); +process.stdin.resume(); +console.error('stdin opened'); +setTimeout(function() { + console.error('pausing stdin'); + process.stdin.pause(); + setTimeout(function() { + console.error('opening again'); + process.stdin.resume(); + setTimeout(function() { + console.error('pausing again'); + process.stdin.pause(); + console.error('should exit now'); + }, 1); + }, 1); +}, 1); diff --git a/test/parallel/test-stdin-resume-pause.js b/test/parallel/test-stdin-resume-pause.js new file mode 100644 index 000000000..2d2af2fc6 --- /dev/null +++ b/test/parallel/test-stdin-resume-pause.js @@ -0,0 +1,23 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +process.stdin.resume(); +process.stdin.pause(); diff --git a/test/parallel/test-stdio-readable-writable.js b/test/parallel/test-stdio-readable-writable.js new file mode 100644 index 000000000..5123f9688 --- /dev/null +++ b/test/parallel/test-stdio-readable-writable.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +assert(process.stdout.writable); +assert(!process.stdout.readable); + +assert(process.stderr.writable); +assert(!process.stderr.readable); + +assert(!process.stdin.writable); +assert(process.stdin.readable); diff --git a/test/parallel/test-stdout-close-unref.js b/test/parallel/test-stdout-close-unref.js new file mode 100644 index 000000000..f8cbc7e4b --- /dev/null +++ b/test/parallel/test-stdout-close-unref.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); + +var errs = 0; + +process.stdin.resume(); +process.stdin._handle.close(); +process.stdin._handle.unref(); // Should not segfault. +process.stdin.on('error', function(err) { + errs++; +}); + +process.on('exit', function() { + assert.strictEqual(errs, 1); +}); diff --git a/test/parallel/test-stream-big-packet.js b/test/parallel/test-stream-big-packet.js new file mode 100644 index 000000000..9ec29ca0d --- /dev/null +++ b/test/parallel/test-stream-big-packet.js @@ -0,0 +1,73 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var stream = require('stream'); + +var passed = false; + +function PassThrough () { + stream.Transform.call(this); +}; +util.inherits(PassThrough, stream.Transform); +PassThrough.prototype._transform = function (chunk, encoding, done) { + this.push(chunk); + done(); +}; + +function TestStream () { + stream.Transform.call(this); +}; +util.inherits(TestStream, stream.Transform); +TestStream.prototype._transform = function (chunk, encoding, done) { + if (!passed) { + // Char 'a' only exists in the last write + passed = chunk.toString().indexOf('a') >= 0; + } + done(); +}; + +var s1 = new PassThrough(); +var s2 = new PassThrough(); +var s3 = new TestStream(); +s1.pipe(s3); +// Don't let s2 auto close which may close s3 +s2.pipe(s3, {end: false}); + +// We must write a buffer larger than highWaterMark +var big = new Buffer(s1._writableState.highWaterMark + 1); +big.fill('x'); + +// Since big is larger than highWaterMark, it will be buffered internally. +assert(!s1.write(big)); +// 'tiny' is small enough to pass through internal buffer. +assert(s2.write('tiny')); + +// Write some small data in next IO loop, which will never be written to s3 +// Because 'drain' event is not emitted from s1 and s1 is still paused +setImmediate(s1.write.bind(s1), 'later'); + +// Assert after two IO loops when all operations have been done. +process.on('exit', function () { + assert(passed, 'Large buffer is not handled properly by Writable Stream'); +}); diff --git a/test/parallel/test-stream-big-push.js b/test/parallel/test-stream-big-push.js new file mode 100644 index 000000000..e3787e441 --- /dev/null +++ b/test/parallel/test-stream-big-push.js @@ -0,0 +1,84 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var stream = require('stream'); +var str = 'asdfasdfasdfasdfasdf'; + +var r = new stream.Readable({ + highWaterMark: 5, + encoding: 'utf8' +}); + +var reads = 0; +var eofed = false; +var ended = false; + +r._read = function(n) { + if (reads === 0) { + setTimeout(function() { + r.push(str); + }); + reads++; + } else if (reads === 1) { + var ret = r.push(str); + assert.equal(ret, false); + reads++; + } else { + assert(!eofed); + eofed = true; + r.push(null); + } +}; + +r.on('end', function() { + ended = true; +}); + +// push some data in to start. +// we've never gotten any read event at this point. +var ret = r.push(str); +// should be false. > hwm +assert(!ret); +var chunk = r.read(); +assert.equal(chunk, str); +chunk = r.read(); +assert.equal(chunk, null); + +r.once('readable', function() { + // this time, we'll get *all* the remaining data, because + // it's been added synchronously, as the read WOULD take + // us below the hwm, and so it triggered a _read() again, + // which synchronously added more, which we then return. + chunk = r.read(); + assert.equal(chunk, str + str); + + chunk = r.read(); + assert.equal(chunk, null); +}); + +process.on('exit', function() { + assert(eofed); + assert(ended); + assert.equal(reads, 2); + console.log('ok'); +}); diff --git a/test/parallel/test-stream-duplex.js b/test/parallel/test-stream-duplex.js new file mode 100644 index 000000000..61f314939 --- /dev/null +++ b/test/parallel/test-stream-duplex.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Duplex = require('stream').Transform; + +var stream = new Duplex({ objectMode: true }); + +assert(stream._readableState.objectMode); +assert(stream._writableState.objectMode); + +var written; +var read; + +stream._write = function (obj, _, cb) { + written = obj; + cb(); +}; + +stream._read = function () {}; + +stream.on('data', function (obj) { + read = obj; +}); + +stream.push({ val: 1 }); +stream.end({ val: 2 }); + +process.on('exit', function () { + assert(read.val === 1); + assert(written.val === 2); +}); diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js new file mode 100644 index 000000000..bb7377776 --- /dev/null +++ b/test/parallel/test-stream-end-paused.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var gotEnd = false; + +// Make sure we don't miss the end event for paused 0-length streams + +var Readable = require('stream').Readable; +var stream = new Readable(); +var calledRead = false; +stream._read = function() { + assert(!calledRead); + calledRead = true; + this.push(null); +}; + +stream.on('data', function() { + throw new Error('should not ever get data'); +}); +stream.pause(); + +setTimeout(function() { + stream.on('end', function() { + gotEnd = true; + }); + stream.resume(); +}); + +process.on('exit', function() { + assert(gotEnd); + assert(calledRead); + console.log('ok'); +}); diff --git a/test/parallel/test-stream-ispaused.js b/test/parallel/test-stream-ispaused.js new file mode 100644 index 000000000..91f4f512f --- /dev/null +++ b/test/parallel/test-stream-ispaused.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. + +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: + +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); + +var stream = require('stream'); + +var readable = new stream.Readable; + +// _read is a noop, here. +readable._read = Function(); + +// default state of a stream is not "paused" +assert.ok(!readable.isPaused()); + +// make the stream start flowing... +readable.on('data', Function()); + +// still not paused. +assert.ok(!readable.isPaused()); + +readable.pause(); +assert.ok(readable.isPaused()); +readable.resume(); +assert.ok(!readable.isPaused()); diff --git a/test/parallel/test-stream-pipe-after-end.js b/test/parallel/test-stream-pipe-after-end.js new file mode 100644 index 000000000..b46ee90ad --- /dev/null +++ b/test/parallel/test-stream-pipe-after-end.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Readable = require('_stream_readable'); +var Writable = require('_stream_writable'); +var util = require('util'); + +util.inherits(TestReadable, Readable); +function TestReadable(opt) { + if (!(this instanceof TestReadable)) + return new TestReadable(opt); + Readable.call(this, opt); + this._ended = false; +} + +TestReadable.prototype._read = function(n) { + if (this._ended) + this.emit('error', new Error('_read called twice')); + this._ended = true; + this.push(null); +}; + +util.inherits(TestWritable, Writable); +function TestWritable(opt) { + if (!(this instanceof TestWritable)) + return new TestWritable(opt); + Writable.call(this, opt); + this._written = []; +} + +TestWritable.prototype._write = function(chunk, encoding, cb) { + this._written.push(chunk); + cb(); +}; + +// this one should not emit 'end' until we read() from it later. +var ender = new TestReadable(); +var enderEnded = false; + +// what happens when you pipe() a Readable that's already ended? +var piper = new TestReadable(); +// pushes EOF null, and length=0, so this will trigger 'end' +piper.read(); + +setTimeout(function() { + ender.on('end', function() { + enderEnded = true; + }); + assert(!enderEnded); + var c = ender.read(); + assert.equal(c, null); + + var w = new TestWritable(); + var writableFinished = false; + w.on('finish', function() { + writableFinished = true; + }); + piper.pipe(w); + + process.on('exit', function() { + assert(enderEnded); + assert(writableFinished); + console.log('ok'); + }); +}); diff --git a/test/parallel/test-stream-pipe-cleanup.js b/test/parallel/test-stream-pipe-cleanup.js new file mode 100644 index 000000000..f68935852 --- /dev/null +++ b/test/parallel/test-stream-pipe-cleanup.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This test asserts that Stream.prototype.pipe does not leave listeners +// hanging on the source or dest. + +var common = require('../common'); +var stream = require('stream'); +var assert = require('assert'); +var util = require('util'); + +function Writable() { + this.writable = true; + this.endCalls = 0; + stream.Stream.call(this); +} +util.inherits(Writable, stream.Stream); +Writable.prototype.end = function() { + this.endCalls++; +}; + +Writable.prototype.destroy = function() { + this.endCalls++; +}; + +function Readable() { + this.readable = true; + stream.Stream.call(this); +} +util.inherits(Readable, stream.Stream); + +function Duplex() { + this.readable = true; + Writable.call(this); +} +util.inherits(Duplex, Writable); + +var i = 0; +var limit = 100; + +var w = new Writable(); + +var r; + +for (i = 0; i < limit; i++) { + r = new Readable(); + r.pipe(w); + r.emit('end'); +} +assert.equal(0, r.listeners('end').length); +assert.equal(limit, w.endCalls); + +w.endCalls = 0; + +for (i = 0; i < limit; i++) { + r = new Readable(); + r.pipe(w); + r.emit('close'); +} +assert.equal(0, r.listeners('close').length); +assert.equal(limit, w.endCalls); + +w.endCalls = 0; + +r = new Readable(); + +for (i = 0; i < limit; i++) { + w = new Writable(); + r.pipe(w); + w.emit('close'); +} +assert.equal(0, w.listeners('close').length); + +r = new Readable(); +w = new Writable(); +var d = new Duplex(); +r.pipe(d); // pipeline A +d.pipe(w); // pipeline B +assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup +assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup +assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup +assert.equal(w.listeners('end').length, 0); +assert.equal(w.listeners('close').length, 1); // B.cleanup + +r.emit('end'); +assert.equal(d.endCalls, 1); +assert.equal(w.endCalls, 0); +assert.equal(r.listeners('end').length, 0); +assert.equal(r.listeners('close').length, 0); +assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup +assert.equal(w.listeners('end').length, 0); +assert.equal(w.listeners('close').length, 1); // B.cleanup + +d.emit('end'); +assert.equal(d.endCalls, 1); +assert.equal(w.endCalls, 1); +assert.equal(r.listeners('end').length, 0); +assert.equal(r.listeners('close').length, 0); +assert.equal(d.listeners('end').length, 0); +assert.equal(d.listeners('close').length, 0); +assert.equal(w.listeners('end').length, 0); +assert.equal(w.listeners('close').length, 0); diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js new file mode 100644 index 000000000..c5d724b78 --- /dev/null +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -0,0 +1,131 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Stream = require('stream').Stream; + +(function testErrorListenerCatches() { + var source = new Stream(); + var dest = new Stream(); + + source.pipe(dest); + + var gotErr = null; + source.on('error', function(err) { + gotErr = err; + }); + + var err = new Error('This stream turned into bacon.'); + source.emit('error', err); + assert.strictEqual(gotErr, err); +})(); + +(function testErrorWithoutListenerThrows() { + var source = new Stream(); + var dest = new Stream(); + + source.pipe(dest); + + var err = new Error('This stream turned into bacon.'); + + var gotErr = null; + try { + source.emit('error', err); + } catch (e) { + gotErr = e; + } + + assert.strictEqual(gotErr, err); +})(); + +(function testErrorWithRemovedListenerThrows() { + var EE = require('events').EventEmitter; + var R = Stream.Readable; + var W = Stream.Writable; + + var r = new R; + var w = new W; + var removed = false; + var didTest = false; + + process.on('exit', function() { + assert(didTest); + console.log('ok'); + }); + + r._read = function() { + setTimeout(function() { + assert(removed); + assert.throws(function() { + w.emit('error', new Error('fail')); + }); + didTest = true; + }); + }; + + w.on('error', myOnError); + r.pipe(w); + w.removeListener('error', myOnError); + removed = true; + + function myOnError(er) { + throw new Error('this should not happen'); + } +})(); + +(function testErrorWithRemovedListenerThrows() { + var EE = require('events').EventEmitter; + var R = Stream.Readable; + var W = Stream.Writable; + + var r = new R; + var w = new W; + var removed = false; + var didTest = false; + var caught = false; + + process.on('exit', function() { + assert(didTest); + console.log('ok'); + }); + + r._read = function() { + setTimeout(function() { + assert(removed); + w.emit('error', new Error('fail')); + didTest = true; + }); + }; + + w.on('error', myOnError); + w._write = function() {}; + + r.pipe(w); + // Removing some OTHER random listener should not do anything + w.removeListener('error', function() {}); + removed = true; + + function myOnError(er) { + assert(!caught); + caught = true; + } +})(); diff --git a/test/parallel/test-stream-pipe-event.js b/test/parallel/test-stream-pipe-event.js new file mode 100644 index 000000000..cb9d5fe8c --- /dev/null +++ b/test/parallel/test-stream-pipe-event.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var stream = require('stream'); +var assert = require('assert'); +var util = require('util'); + +function Writable() { + this.writable = true; + stream.Stream.call(this); +} +util.inherits(Writable, stream.Stream); + +function Readable() { + this.readable = true; + stream.Stream.call(this); +} +util.inherits(Readable, stream.Stream); + +var passed = false; + +var w = new Writable(); +w.on('pipe', function(src) { + passed = true; +}); + +var r = new Readable(); +r.pipe(w); + +assert.ok(passed); diff --git a/test/parallel/test-stream-push-order.js b/test/parallel/test-stream-push-order.js new file mode 100644 index 000000000..f2e6ec29c --- /dev/null +++ b/test/parallel/test-stream-push-order.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var Readable = require('stream').Readable; +var assert = require('assert'); + +var s = new Readable({ + highWaterMark: 20, + encoding: 'ascii' +}); + +var list = ['1', '2', '3', '4', '5', '6']; + +s._read = function (n) { + var one = list.shift(); + if (!one) { + s.push(null); + } else { + var two = list.shift(); + s.push(one); + s.push(two); + } +}; + +var v = s.read(0); + +// ACTUALLY [1, 3, 5, 6, 4, 2] + +process.on("exit", function () { + assert.deepEqual(s._readableState.buffer, + ['1', '2', '3', '4', '5', '6']); + console.log("ok"); +}); diff --git a/test/parallel/test-stream-push-strings.js b/test/parallel/test-stream-push-strings.js new file mode 100644 index 000000000..06f43dc1c --- /dev/null +++ b/test/parallel/test-stream-push-strings.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Readable = require('stream').Readable; +var util = require('util'); + +util.inherits(MyStream, Readable); +function MyStream(options) { + Readable.call(this, options); + this._chunks = 3; +} + +MyStream.prototype._read = function(n) { + switch (this._chunks--) { + case 0: + return this.push(null); + case 1: + return setTimeout(function() { + this.push('last chunk'); + }.bind(this), 100); + case 2: + return this.push('second to last chunk'); + case 3: + return process.nextTick(function() { + this.push('first chunk'); + }.bind(this)); + default: + throw new Error('?'); + } +}; + +var ms = new MyStream(); +var results = []; +ms.on('readable', function() { + var chunk; + while (null !== (chunk = ms.read())) + results.push(chunk + ''); +}); + +var expect = [ 'first chunksecond to last chunk', 'last chunk' ]; +process.on('exit', function() { + assert.equal(ms._chunks, -1); + assert.deepEqual(results, expect); + console.log('ok'); +}); diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js new file mode 100644 index 000000000..ba6a57724 --- /dev/null +++ b/test/parallel/test-stream-readable-event.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Readable = require('stream').Readable; + +(function first() { + // First test, not reading when the readable is added. + // make sure that on('readable', ...) triggers a readable event. + var r = new Readable({ + highWaterMark: 3 + }); + + var _readCalled = false; + r._read = function(n) { + _readCalled = true; + }; + + // This triggers a 'readable' event, which is lost. + r.push(new Buffer('blerg')); + + var caughtReadable = false; + setTimeout(function() { + // we're testing what we think we are + assert(!r._readableState.reading); + r.on('readable', function() { + caughtReadable = true; + }); + }); + + process.on('exit', function() { + // we're testing what we think we are + assert(!_readCalled); + + assert(caughtReadable); + console.log('ok 1'); + }); +})(); + +(function second() { + // second test, make sure that readable is re-emitted if there's + // already a length, while it IS reading. + + var r = new Readable({ + highWaterMark: 3 + }); + + var _readCalled = false; + r._read = function(n) { + _readCalled = true; + }; + + // This triggers a 'readable' event, which is lost. + r.push(new Buffer('bl')); + + var caughtReadable = false; + setTimeout(function() { + // assert we're testing what we think we are + assert(r._readableState.reading); + r.on('readable', function() { + caughtReadable = true; + }); + }); + + process.on('exit', function() { + // we're testing what we think we are + assert(_readCalled); + + assert(caughtReadable); + console.log('ok 2'); + }); +})(); + +(function third() { + // Third test, not reading when the stream has not passed + // the highWaterMark but *has* reached EOF. + var r = new Readable({ + highWaterMark: 30 + }); + + var _readCalled = false; + r._read = function(n) { + _readCalled = true; + }; + + // This triggers a 'readable' event, which is lost. + r.push(new Buffer('blerg')); + r.push(null); + + var caughtReadable = false; + setTimeout(function() { + // assert we're testing what we think we are + assert(!r._readableState.reading); + r.on('readable', function() { + caughtReadable = true; + }); + }); + + process.on('exit', function() { + // we're testing what we think we are + assert(!_readCalled); + + assert(caughtReadable); + console.log('ok 3'); + }); +})(); diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js new file mode 100644 index 000000000..2891ad6db --- /dev/null +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// this test verifies that passing a huge number to read(size) +// will push up the highWaterMark, and cause the stream to read +// more data continuously, but without triggering a nextTick +// warning or RangeError. + +var Readable = require('stream').Readable; + +// throw an error if we trigger a nextTick warning. +process.throwDeprecation = true; + +var stream = new Readable({ highWaterMark: 2 }); +var reads = 0; +var total = 5000; +stream._read = function(size) { + reads++; + size = Math.min(size, total); + total -= size; + if (size === 0) + stream.push(null); + else + stream.push(new Buffer(size)); +}; + +var depth = 0; + +function flow(stream, size, callback) { + depth += 1; + var chunk = stream.read(size); + + if (!chunk) + stream.once('readable', flow.bind(null, stream, size, callback)); + else + callback(chunk); + + depth -= 1; + console.log('flow(' + depth + '): exit'); +} + +flow(stream, 5000, function() { + console.log('complete (' + depth + ')'); +}); + +process.on('exit', function(code) { + assert.equal(reads, 2); + // we pushed up the high water mark + assert.equal(stream._readableState.highWaterMark, 8192); + // length is 0 right now, because we pulled it all out. + assert.equal(stream._readableState.length, 0); + assert(!code); + assert.equal(depth, 0); + console.log('ok'); +}); diff --git a/test/parallel/test-stream-transform-objectmode-falsey-value.js b/test/parallel/test-stream-transform-objectmode-falsey-value.js new file mode 100644 index 000000000..31b5bbaaf --- /dev/null +++ b/test/parallel/test-stream-transform-objectmode-falsey-value.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var stream = require('stream'); +var PassThrough = stream.PassThrough; + +var src = new PassThrough({ objectMode: true }); +var tx = new PassThrough({ objectMode: true }); +var dest = new PassThrough({ objectMode: true }); + +var expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; +var results = []; +process.on('exit', function() { + assert.deepEqual(results, expect); + console.log('ok'); +}); + +dest.on('data', function(x) { + results.push(x); +}); + +src.pipe(tx).pipe(dest); + +var i = -1; +var int = setInterval(function() { + if (i > 10) { + src.end(); + clearInterval(int); + } else { + src.write(i++); + } +}); diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js new file mode 100644 index 000000000..72a2f0ace --- /dev/null +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Transform = require('stream').Transform; + +var parser = new Transform({ readableObjectMode : true }); + +assert(parser._readableState.objectMode); +assert(!parser._writableState.objectMode); +assert(parser._readableState.highWaterMark === 16); +assert(parser._writableState.highWaterMark === (16 * 1024)); + +parser._transform = function (chunk, enc, callback) { + callback(null, { val : chunk[0] }); +}; + +var parsed; + +parser.on('data', function (obj) { + parsed = obj; +}); + +parser.end(new Buffer([42])); + +process.on('exit', function () { + assert(parsed.val === 42); +}); + + +var serializer = new Transform({ writableObjectMode : true }); + +assert(!serializer._readableState.objectMode); +assert(serializer._writableState.objectMode); +assert(serializer._readableState.highWaterMark === (16 * 1024)); +assert(serializer._writableState.highWaterMark === 16); + +serializer._transform = function (obj, _, callback) { + callback(null, new Buffer([obj.val])); +}; + +var serialized; + +serializer.on('data', function (chunk) { + serialized = chunk; +}); + +serializer.write({ val : 42 }); + +process.on('exit', function () { + assert(serialized[0] === 42); +}); diff --git a/test/parallel/test-stream-unshift-empty-chunk.js b/test/parallel/test-stream-unshift-empty-chunk.js new file mode 100644 index 000000000..0c9647650 --- /dev/null +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -0,0 +1,81 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// This test verifies that stream.unshift(Buffer(0)) or +// stream.unshift('') does not set state.reading=false. +var Readable = require('stream').Readable; + +var r = new Readable(); +var nChunks = 10; +var chunk = new Buffer(10); +chunk.fill('x'); + +r._read = function(n) { + setTimeout(function() { + r.push(--nChunks === 0 ? null : chunk); + }); +}; + +var readAll = false; +var seen = []; +r.on('readable', function() { + var chunk; + while (chunk = r.read()) { + seen.push(chunk.toString()); + // simulate only reading a certain amount of the data, + // and then putting the rest of the chunk back into the + // stream, like a parser might do. We just fill it with + // 'y' so that it's easy to see which bits were touched, + // and which were not. + var putBack = new Buffer(readAll ? 0 : 5); + putBack.fill('y'); + readAll = !readAll; + r.unshift(putBack); + } +}); + +var expect = + [ 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy', + 'xxxxxxxxxx', + 'yyyyy' ]; + +r.on('end', function() { + assert.deepEqual(seen, expect); + console.log('ok'); +}); diff --git a/test/parallel/test-stream-unshift-read-race.js b/test/parallel/test-stream-unshift-read-race.js new file mode 100644 index 000000000..83fd9fa20 --- /dev/null +++ b/test/parallel/test-stream-unshift-read-race.js @@ -0,0 +1,133 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// This test verifies that: +// 1. unshift() does not cause colliding _read() calls. +// 2. unshift() after the 'end' event is an error, but after the EOF +// signalling null, it is ok, and just creates a new readable chunk. +// 3. push() after the EOF signaling null is an error. +// 4. _read() is not called after pushing the EOF null chunk. + +var stream = require('stream'); +var hwm = 10; +var r = stream.Readable({ highWaterMark: hwm }); +var chunks = 10; +var t = (chunks * 5); + +var data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)); +for (var i = 0; i < data.length; i++) { + var c = 'asdf'.charCodeAt(i % 4); + data[i] = c; +} + +var pos = 0; +var pushedNull = false; +r._read = function(n) { + assert(!pushedNull, '_read after null push'); + + // every third chunk is fast + push(!(chunks % 3)); + + function push(fast) { + assert(!pushedNull, 'push() after null push'); + var c = pos >= data.length ? null : data.slice(pos, pos + n); + pushedNull = c === null; + if (fast) { + pos += n; + r.push(c); + if (c === null) pushError(); + } else { + setTimeout(function() { + pos += n; + r.push(c); + if (c === null) pushError(); + }); + } + } +}; + +function pushError() { + assert.throws(function() { + r.push(new Buffer(1)); + }); +} + + +var w = stream.Writable(); +var written = []; +w._write = function(chunk, encoding, cb) { + written.push(chunk.toString()); + cb(); +}; + +var ended = false; +r.on('end', function() { + assert(!ended, 'end emitted more than once'); + assert.throws(function() { + r.unshift(new Buffer(1)); + }); + ended = true; + w.end(); +}); + +r.on('readable', function() { + var chunk; + while (null !== (chunk = r.read(10))) { + w.write(chunk); + if (chunk.length > 4) + r.unshift(new Buffer('1234')); + } +}); + +var finished = false; +w.on('finish', function() { + finished = true; + // each chunk should start with 1234, and then be asfdasdfasdf... + // The first got pulled out before the first unshift('1234'), so it's + // lacking that piece. + assert.equal(written[0], 'asdfasdfas'); + var asdf = 'd'; + console.error('0: %s', written[0]); + for (var i = 1; i < written.length; i++) { + console.error('%s: %s', i.toString(32), written[i]); + assert.equal(written[i].slice(0, 4), '1234'); + for (var j = 4; j < written[i].length; j++) { + var c = written[i].charAt(j); + assert.equal(c, asdf); + switch (asdf) { + case 'a': asdf = 's'; break; + case 's': asdf = 'd'; break; + case 'd': asdf = 'f'; break; + case 'f': asdf = 'a'; break; + } + } + } +}); + +process.on('exit', function() { + assert.equal(written.length, 18); + assert(ended, 'stream ended'); + assert(finished, 'stream finished'); + console.log('ok'); +}); diff --git a/test/parallel/test-stream-writable-change-default-encoding.js b/test/parallel/test-stream-writable-change-default-encoding.js new file mode 100644 index 000000000..eb71cf2b4 --- /dev/null +++ b/test/parallel/test-stream-writable-change-default-encoding.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var stream = require('stream'); +var util = require('util'); + +function MyWritable(fn, options) { + stream.Writable.call(this, options); + this.fn = fn; +}; + +util.inherits(MyWritable, stream.Writable); + +MyWritable.prototype._write = function (chunk, encoding, callback) { + this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); + callback(); +}; + +(function defaultCondingIsUtf8() { + var m = new MyWritable(function(isBuffer, type, enc) { + assert.equal(enc, 'utf8'); + }, { decodeStrings: false }); + m.write('foo'); + m.end(); +}()); + +(function changeDefaultEncodingToAscii() { + var m = new MyWritable(function(isBuffer, type, enc) { + assert.equal(enc, 'ascii'); + }, { decodeStrings: false }); + m.setDefaultEncoding('ascii'); + m.write('bar'); + m.end(); +}()); + +assert.throws(function changeDefaultEncodingToInvalidValue() { + var m = new MyWritable(function(isBuffer, type, enc) { + }, { decodeStrings: false }); + m.setDefaultEncoding({}); + m.write('bar'); + m.end(); +}, TypeError); + +(function checkVairableCaseEncoding() { + var m = new MyWritable(function(isBuffer, type, enc) { + assert.equal(enc, 'ascii'); + }, { decodeStrings: false }); + m.setDefaultEncoding('AsCii'); + m.write('bar'); + m.end(); +}()); diff --git a/test/parallel/test-stream-writable-decoded-encoding.js b/test/parallel/test-stream-writable-decoded-encoding.js new file mode 100644 index 000000000..8e2624b25 --- /dev/null +++ b/test/parallel/test-stream-writable-decoded-encoding.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var stream = require('stream'); +var util = require('util'); + +function MyWritable(fn, options) { + stream.Writable.call(this, options); + this.fn = fn; +}; + +util.inherits(MyWritable, stream.Writable); + +MyWritable.prototype._write = function (chunk, encoding, callback) { + this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); + callback(); +}; + +;(function decodeStringsTrue() { + var m = new MyWritable(function(isBuffer, type, enc) { + assert(isBuffer); + assert.equal(type, 'object'); + assert.equal(enc, 'buffer'); + console.log('ok - decoded string is decoded'); + }, { decodeStrings: true }); + m.write('some-text', 'utf8'); + m.end(); +})(); + +;(function decodeStringsFalse() { + var m = new MyWritable(function(isBuffer, type, enc) { + assert(!isBuffer); + assert.equal(type, 'string'); + assert.equal(enc, 'utf8'); + console.log('ok - un-decoded string is not decoded'); + }, { decodeStrings: false }); + m.write('some-text', 'utf8'); + m.end(); +})(); diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js new file mode 100644 index 000000000..5b49e6e41 --- /dev/null +++ b/test/parallel/test-stream-writev.js @@ -0,0 +1,121 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var stream = require('stream'); + +var queue = []; +for (var decode = 0; decode < 2; decode++) { + for (var uncork = 0; uncork < 2; uncork++) { + for (var multi = 0; multi < 2; multi++) { + queue.push([!!decode, !!uncork, !!multi]); + } + } +} + +run(); + +function run() { + var t = queue.pop(); + if (t) + test(t[0], t[1], t[2], run); + else + console.log('ok'); +} + +function test(decode, uncork, multi, next) { + console.log('# decode=%j uncork=%j multi=%j', decode, uncork, multi); + var counter = 0; + var expectCount = 0; + function cnt(msg) { + expectCount++; + var expect = expectCount; + var called = false; + return function(er) { + if (er) + throw er; + called = true; + counter++; + assert.equal(counter, expect); + }; + } + + var w = new stream.Writable({ decodeStrings: decode }); + w._write = function(chunk, e, cb) { + assert(false, 'Should not call _write'); + }; + + var expectChunks = decode ? + [{ encoding: 'buffer', + chunk: [104, 101, 108, 108, 111, 44, 32] }, + { encoding: 'buffer', chunk: [119, 111, 114, 108, 100] }, + { encoding: 'buffer', chunk: [33] }, + { encoding: 'buffer', + chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, + { encoding: 'buffer', + chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173] }] : + [{ encoding: 'ascii', chunk: 'hello, ' }, + { encoding: 'utf8', chunk: 'world' }, + { encoding: 'buffer', chunk: [33] }, + { encoding: 'binary', chunk: '\nand then...' }, + { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' }]; + + var actualChunks; + w._writev = function(chunks, cb) { + actualChunks = chunks.map(function(chunk) { + return { + encoding: chunk.encoding, + chunk: Buffer.isBuffer(chunk.chunk) ? + Array.prototype.slice.call(chunk.chunk) : chunk.chunk + }; + }); + cb(); + }; + + w.cork(); + w.write('hello, ', 'ascii', cnt('hello')); + w.write('world', 'utf8', cnt('world')); + + if (multi) + w.cork(); + + w.write(new Buffer('!'), 'buffer', cnt('!')); + w.write('\nand then...', 'binary', cnt('and then')); + + if (multi) + w.uncork(); + + w.write('facebea7deadbeefdecafbad', 'hex', cnt('hex')); + + if (uncork) + w.uncork(); + + w.end(cnt('end')); + + w.on('finish', function() { + // make sure finish comes after all the write cb + cnt('finish')(); + assert.deepEqual(expectChunks, actualChunks); + next(); + }); +} diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js new file mode 100644 index 000000000..5a3834128 --- /dev/null +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var R = require('_stream_readable'); +var W = require('_stream_writable'); +var assert = require('assert'); + +var src = new R({encoding: 'base64'}); +var dst = new W(); +var hasRead = false; +var accum = []; +var timeout; + +src._read = function(n) { + if(!hasRead) { + hasRead = true; + process.nextTick(function() { + src.push(new Buffer('1')); + src.push(null); + }); + }; +}; + +dst._write = function(chunk, enc, cb) { + accum.push(chunk); + cb(); +}; + +src.on('end', function() { + assert.equal(Buffer.concat(accum) + '', 'MQ=='); + clearTimeout(timeout); +}) + +src.pipe(dst); + +timeout = setTimeout(function() { + assert.fail('timed out waiting for _write'); +}, 100); diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js new file mode 100644 index 000000000..6cdd4e994 --- /dev/null +++ b/test/parallel/test-stream2-compatibility.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var R = require('_stream_readable'); +var assert = require('assert'); + +var util = require('util'); +var EE = require('events').EventEmitter; + +var ondataCalled = 0; + +function TestReader() { + R.apply(this); + this._buffer = new Buffer(100); + this._buffer.fill('x'); + + this.on('data', function() { + ondataCalled++; + }); +} + +util.inherits(TestReader, R); + +TestReader.prototype._read = function(n) { + this.push(this._buffer); + this._buffer = new Buffer(0); +}; + +var reader = new TestReader(); +setImmediate(function() { + assert.equal(ondataCalled, 1); + console.log('ok'); +}); diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js new file mode 100644 index 000000000..39b274f97 --- /dev/null +++ b/test/parallel/test-stream2-finish-pipe.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var stream = require('stream'); +var Buffer = require('buffer').Buffer; + +var r = new stream.Readable(); +r._read = function(size) { + r.push(new Buffer(size)); +}; + +var w = new stream.Writable(); +w._write = function(data, encoding, cb) { + cb(null); +}; + +r.pipe(w); + +// This might sound unrealistic, but it happens in net.js. When +// `socket.allowHalfOpen === false`, EOF will cause `.destroySoon()` call which +// ends the writable side of net.Socket. +w.end(); diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js new file mode 100644 index 000000000..2fbfbcab3 --- /dev/null +++ b/test/parallel/test-stream2-large-read-stall.js @@ -0,0 +1,82 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); + +// If everything aligns so that you do a read(n) of exactly the +// remaining buffer, then make sure that 'end' still emits. + +var READSIZE = 100; +var PUSHSIZE = 20; +var PUSHCOUNT = 1000; +var HWM = 50; + +var Readable = require('stream').Readable; +var r = new Readable({ + highWaterMark: HWM +}); +var rs = r._readableState; + +r._read = push; + +r.on('readable', function() { + console.error('>> readable'); + do { + console.error(' > read(%d)', READSIZE); + var ret = r.read(READSIZE); + console.error(' < %j (%d remain)', ret && ret.length, rs.length); + } while (ret && ret.length === READSIZE); + + console.error('<< after read()', + ret && ret.length, + rs.needReadable, + rs.length); +}); + +var endEmitted = false; +r.on('end', function() { + endEmitted = true; + console.error('end'); +}); + +var pushes = 0; +function push() { + if (pushes > PUSHCOUNT) + return; + + if (pushes++ === PUSHCOUNT) { + console.error(' push(EOF)'); + return r.push(null); + } + + console.error(' push #%d', pushes); + if (r.push(new Buffer(PUSHSIZE))) + setTimeout(push); +} + +// start the flow +var ret = r.read(0); + +process.on('exit', function() { + assert.equal(pushes, PUSHCOUNT + 1); + assert(endEmitted); +}); diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js new file mode 100644 index 000000000..3e6931dce --- /dev/null +++ b/test/parallel/test-stream2-objects.js @@ -0,0 +1,351 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var Readable = require('_stream_readable'); +var Writable = require('_stream_writable'); +var assert = require('assert'); + +// tiny node-tap lookalike. +var tests = []; +var count = 0; + +function test(name, fn) { + count++; + tests.push([name, fn]); +} + +function run() { + var next = tests.shift(); + if (!next) + return console.error('ok'); + + var name = next[0]; + var fn = next[1]; + console.log('# %s', name); + fn({ + same: assert.deepEqual, + equal: assert.equal, + end: function() { + count--; + run(); + } + }); +} + +// ensure all tests have run +process.on('exit', function() { + assert.equal(count, 0); +}); + +process.nextTick(run); + +function toArray(callback) { + var stream = new Writable({ objectMode: true }); + var list = []; + stream.write = function(chunk) { + list.push(chunk); + }; + + stream.end = function() { + callback(list); + }; + + return stream; +} + +function fromArray(list) { + var r = new Readable({ objectMode: true }); + r._read = noop; + list.forEach(function(chunk) { + r.push(chunk); + }); + r.push(null); + + return r; +} + +function noop() {} + +test('can read objects from stream', function(t) { + var r = fromArray([{ one: '1'}, { two: '2' }]); + + var v1 = r.read(); + var v2 = r.read(); + var v3 = r.read(); + + assert.deepEqual(v1, { one: '1' }); + assert.deepEqual(v2, { two: '2' }); + assert.deepEqual(v3, null); + + t.end(); +}); + +test('can pipe objects into stream', function(t) { + var r = fromArray([{ one: '1'}, { two: '2' }]); + + r.pipe(toArray(function(list) { + assert.deepEqual(list, [ + { one: '1' }, + { two: '2' } + ]); + + t.end(); + })); +}); + +test('read(n) is ignored', function(t) { + var r = fromArray([{ one: '1'}, { two: '2' }]); + + var value = r.read(2); + + assert.deepEqual(value, { one: '1' }); + + t.end(); +}); + +test('can read objects from _read (sync)', function(t) { + var r = new Readable({ objectMode: true }); + var list = [{ one: '1'}, { two: '2' }]; + r._read = function(n) { + var item = list.shift(); + r.push(item || null); + }; + + r.pipe(toArray(function(list) { + assert.deepEqual(list, [ + { one: '1' }, + { two: '2' } + ]); + + t.end(); + })); +}); + +test('can read objects from _read (async)', function(t) { + var r = new Readable({ objectMode: true }); + var list = [{ one: '1'}, { two: '2' }]; + r._read = function(n) { + var item = list.shift(); + process.nextTick(function() { + r.push(item || null); + }); + }; + + r.pipe(toArray(function(list) { + assert.deepEqual(list, [ + { one: '1' }, + { two: '2' } + ]); + + t.end(); + })); +}); + +test('can read strings as objects', function(t) { + var r = new Readable({ + objectMode: true + }); + r._read = noop; + var list = ['one', 'two', 'three']; + list.forEach(function(str) { + r.push(str); + }); + r.push(null); + + r.pipe(toArray(function(array) { + assert.deepEqual(array, list); + + t.end(); + })); +}); + +test('read(0) for object streams', function(t) { + var r = new Readable({ + objectMode: true + }); + r._read = noop; + + r.push('foobar'); + r.push(null); + + var v = r.read(0); + + r.pipe(toArray(function(array) { + assert.deepEqual(array, ['foobar']); + + t.end(); + })); +}); + +test('falsey values', function(t) { + var r = new Readable({ + objectMode: true + }); + r._read = noop; + + r.push(false); + r.push(0); + r.push(''); + r.push(null); + + r.pipe(toArray(function(array) { + assert.deepEqual(array, [false, 0, '']); + + t.end(); + })); +}); + +test('high watermark _read', function(t) { + var r = new Readable({ + highWaterMark: 6, + objectMode: true + }); + var calls = 0; + var list = ['1', '2', '3', '4', '5', '6', '7', '8']; + + r._read = function(n) { + calls++; + }; + + list.forEach(function(c) { + r.push(c); + }); + + var v = r.read(); + + assert.equal(calls, 0); + assert.equal(v, '1'); + + var v2 = r.read(); + assert.equal(v2, '2'); + + var v3 = r.read(); + assert.equal(v3, '3'); + + assert.equal(calls, 1); + + t.end(); +}); + +test('high watermark push', function(t) { + var r = new Readable({ + highWaterMark: 6, + objectMode: true + }); + r._read = function(n) {}; + for (var i = 0; i < 6; i++) { + var bool = r.push(i); + assert.equal(bool, i === 5 ? false : true); + } + + t.end(); +}); + +test('can write objects to stream', function(t) { + var w = new Writable({ objectMode: true }); + + w._write = function(chunk, encoding, cb) { + assert.deepEqual(chunk, { foo: 'bar' }); + cb(); + }; + + w.on('finish', function() { + t.end(); + }); + + w.write({ foo: 'bar' }); + w.end(); +}); + +test('can write multiple objects to stream', function(t) { + var w = new Writable({ objectMode: true }); + var list = []; + + w._write = function(chunk, encoding, cb) { + list.push(chunk); + cb(); + }; + + w.on('finish', function() { + assert.deepEqual(list, [0, 1, 2, 3, 4]); + + t.end(); + }); + + w.write(0); + w.write(1); + w.write(2); + w.write(3); + w.write(4); + w.end(); +}); + +test('can write strings as objects', function(t) { + var w = new Writable({ + objectMode: true + }); + var list = []; + + w._write = function(chunk, encoding, cb) { + list.push(chunk); + process.nextTick(cb); + }; + + w.on('finish', function() { + assert.deepEqual(list, ['0', '1', '2', '3', '4']); + + t.end(); + }); + + w.write('0'); + w.write('1'); + w.write('2'); + w.write('3'); + w.write('4'); + w.end(); +}); + +test('buffers finish until cb is called', function(t) { + var w = new Writable({ + objectMode: true + }); + var called = false; + + w._write = function(chunk, encoding, cb) { + assert.equal(chunk, 'foo'); + + process.nextTick(function() { + called = true; + cb(); + }); + }; + + w.on('finish', function() { + assert.equal(called, true); + + t.end(); + }); + + w.write('foo'); + w.end(); +}); diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js new file mode 100644 index 000000000..cf7531cbd --- /dev/null +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -0,0 +1,105 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var stream = require('stream'); + +(function testErrorListenerCatches() { + var count = 1000; + + var source = new stream.Readable(); + source._read = function(n) { + n = Math.min(count, n); + count -= n; + source.push(new Buffer(n)); + }; + + var unpipedDest; + source.unpipe = function(dest) { + unpipedDest = dest; + stream.Readable.prototype.unpipe.call(this, dest); + }; + + var dest = new stream.Writable(); + dest._write = function(chunk, encoding, cb) { + cb(); + }; + + source.pipe(dest); + + var gotErr = null; + dest.on('error', function(err) { + gotErr = err; + }); + + var unpipedSource; + dest.on('unpipe', function(src) { + unpipedSource = src; + }); + + var err = new Error('This stream turned into bacon.'); + dest.emit('error', err); + assert.strictEqual(gotErr, err); + assert.strictEqual(unpipedSource, source); + assert.strictEqual(unpipedDest, dest); +})(); + +(function testErrorWithoutListenerThrows() { + var count = 1000; + + var source = new stream.Readable(); + source._read = function(n) { + n = Math.min(count, n); + count -= n; + source.push(new Buffer(n)); + }; + + var unpipedDest; + source.unpipe = function(dest) { + unpipedDest = dest; + stream.Readable.prototype.unpipe.call(this, dest); + }; + + var dest = new stream.Writable(); + dest._write = function(chunk, encoding, cb) { + cb(); + }; + + source.pipe(dest); + + var unpipedSource; + dest.on('unpipe', function(src) { + unpipedSource = src; + }); + + var err = new Error('This stream turned into bacon.'); + + var gotErr = null; + try { + dest.emit('error', err); + } catch (e) { + gotErr = e; + } + assert.strictEqual(gotErr, err); + assert.strictEqual(unpipedSource, source); + assert.strictEqual(unpipedDest, dest); +})(); diff --git a/test/parallel/test-stream2-pipe-error-once-listener.js b/test/parallel/test-stream2-pipe-error-once-listener.js new file mode 100755 index 000000000..5e8e3cb28 --- /dev/null +++ b/test/parallel/test-stream2-pipe-error-once-listener.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var assert = require('assert'); + +var util = require('util'); +var stream = require('stream'); + + +var Read = function() { + stream.Readable.call(this); +}; +util.inherits(Read, stream.Readable); + +Read.prototype._read = function(size) { + this.push('x'); + this.push(null); +}; + + +var Write = function() { + stream.Writable.call(this); +}; +util.inherits(Write, stream.Writable); + +Write.prototype._write = function(buffer, encoding, cb) { + this.emit('error', new Error('boom')); + this.emit('alldone'); +}; + +var read = new Read(); +var write = new Write(); + +write.once('error', function(err) {}); +write.once('alldone', function(err) { + console.log('ok'); +}); + +process.on('exit', function(c) { + console.error('error thrown even with listener'); +}); + +read.pipe(write); + diff --git a/test/parallel/test-stream2-push.js b/test/parallel/test-stream2-push.js new file mode 100644 index 000000000..b63edc308 --- /dev/null +++ b/test/parallel/test-stream2-push.js @@ -0,0 +1,138 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var stream = require('stream'); +var Readable = stream.Readable; +var Writable = stream.Writable; +var assert = require('assert'); + +var util = require('util'); +var EE = require('events').EventEmitter; + + +// a mock thing a bit like the net.Socket/tcp_wrap.handle interaction + +var stream = new Readable({ + highWaterMark: 16, + encoding: 'utf8' +}); + +var source = new EE; + +stream._read = function() { + console.error('stream._read'); + readStart(); +}; + +var ended = false; +stream.on('end', function() { + ended = true; +}); + +source.on('data', function(chunk) { + var ret = stream.push(chunk); + console.error('data', stream._readableState.length); + if (!ret) + readStop(); +}); + +source.on('end', function() { + stream.push(null); +}); + +var reading = false; + +function readStart() { + console.error('readStart'); + reading = true; +} + +function readStop() { + console.error('readStop'); + reading = false; + process.nextTick(function() { + var r = stream.read(); + if (r !== null) + writer.write(r); + }); +} + +var writer = new Writable({ + decodeStrings: false +}); + +var written = []; + +var expectWritten = + [ 'asdfgasdfgasdfgasdfg', + 'asdfgasdfgasdfgasdfg', + 'asdfgasdfgasdfgasdfg', + 'asdfgasdfgasdfgasdfg', + 'asdfgasdfgasdfgasdfg', + 'asdfgasdfgasdfgasdfg' ]; + +writer._write = function(chunk, encoding, cb) { + console.error('WRITE %s', chunk); + written.push(chunk); + process.nextTick(cb); +}; + +writer.on('finish', finish); + + +// now emit some chunks. + +var chunk = "asdfg"; + +var set = 0; +readStart(); +data(); +function data() { + assert(reading); + source.emit('data', chunk); + assert(reading); + source.emit('data', chunk); + assert(reading); + source.emit('data', chunk); + assert(reading); + source.emit('data', chunk); + assert(!reading); + if (set++ < 5) + setTimeout(data, 10); + else + end(); +} + +function finish() { + console.error('finish'); + assert.deepEqual(written, expectWritten); + console.log('ok'); +} + +function end() { + source.emit('end'); + assert(!reading); + writer.end(stream.read()); + setTimeout(function() { + assert(ended); + }); +} diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js new file mode 100644 index 000000000..e8a73053c --- /dev/null +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Readable = require('stream').Readable; +var r = new Readable(); +var N = 256 * 1024; + +// Go ahead and allow the pathological case for this test. +// Yes, it's an infinite loop, that's the point. +process.maxTickDepth = N + 2; + +var reads = 0; +r._read = function(n) { + var chunk = reads++ === N ? null : new Buffer(1); + r.push(chunk); +}; + +r.on('readable', function onReadable() { + if (!(r._readableState.length % 256)) + console.error('readable', r._readableState.length); + r.read(N * 2); +}); + +var ended = false; +r.on('end', function onEnd() { + ended = true; +}); + +r.read(0); + +process.on('exit', function() { + assert(ended); + console.log('ok'); +}); diff --git a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js new file mode 100644 index 000000000..d52af5edb --- /dev/null +++ b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js @@ -0,0 +1,118 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Readable = require('stream').Readable; + +test1(); +test2(); + +function test1() { + var r = new Readable(); + + // should not end when we get a Buffer(0) or '' as the _read result + // that just means that there is *temporarily* no data, but to go + // ahead and try again later. + // + // note that this is very unusual. it only works for crypto streams + // because the other side of the stream will call read(0) to cycle + // data through openssl. that's why we set the timeouts to call + // r.read(0) again later, otherwise there is no more work being done + // and the process just exits. + + var buf = new Buffer(5); + buf.fill('x'); + var reads = 5; + r._read = function(n) { + switch (reads--) { + case 0: + return r.push(null); // EOF + case 1: + return r.push(buf); + case 2: + setTimeout(r.read.bind(r, 0), 50); + return r.push(new Buffer(0)); // Not-EOF! + case 3: + setTimeout(r.read.bind(r, 0), 50); + return process.nextTick(function() { + return r.push(new Buffer(0)); + }); + case 4: + setTimeout(r.read.bind(r, 0), 50); + return setTimeout(function() { + return r.push(new Buffer(0)); + }); + case 5: + return setTimeout(function() { + return r.push(buf); + }); + default: + throw new Error('unreachable'); + } + }; + + var results = []; + function flow() { + var chunk; + while (null !== (chunk = r.read())) + results.push(chunk + ''); + } + r.on('readable', flow); + r.on('end', function() { + results.push('EOF'); + }); + flow(); + + process.on('exit', function() { + assert.deepEqual(results, [ 'xxxxx', 'xxxxx', 'EOF' ]); + console.log('ok'); + }); +} + +function test2() { + var r = new Readable({ encoding: 'base64' }); + var reads = 5; + r._read = function(n) { + if (!reads--) + return r.push(null); // EOF + else + return r.push(new Buffer('x')); + }; + + var results = []; + function flow() { + var chunk; + while (null !== (chunk = r.read())) + results.push(chunk + ''); + } + r.on('readable', flow); + r.on('end', function() { + results.push('EOF'); + }); + flow(); + + process.on('exit', function() { + assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); + console.log('ok'); + }); +} diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js new file mode 100644 index 000000000..7c96ffe00 --- /dev/null +++ b/test/parallel/test-stream2-readable-from-list.js @@ -0,0 +1,120 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common.js'); +var fromList = require('_stream_readable')._fromList; + +// tiny node-tap lookalike. +var tests = []; +var count = 0; + +function test(name, fn) { + count++; + tests.push([name, fn]); +} + +function run() { + var next = tests.shift(); + if (!next) + return console.error('ok'); + + var name = next[0]; + var fn = next[1]; + console.log('# %s', name); + fn({ + same: assert.deepEqual, + equal: assert.equal, + end: function () { + count--; + run(); + } + }); +} + +// ensure all tests have run +process.on("exit", function () { + assert.equal(count, 0); +}); + +process.nextTick(run); + + + +test('buffers', function(t) { + // have a length + var len = 16; + var list = [ new Buffer('foog'), + new Buffer('bark'), + new Buffer('bazy'), + new Buffer('kuel') ]; + + // read more than the first element. + var ret = fromList(6, { buffer: list, length: 16 }); + t.equal(ret.toString(), 'foogba'); + + // read exactly the first element. + ret = fromList(2, { buffer: list, length: 10 }); + t.equal(ret.toString(), 'rk'); + + // read less than the first element. + ret = fromList(2, { buffer: list, length: 8 }); + t.equal(ret.toString(), 'ba'); + + // read more than we have. + ret = fromList(100, { buffer: list, length: 6 }); + t.equal(ret.toString(), 'zykuel'); + + // all consumed. + t.same(list, []); + + t.end(); +}); + +test('strings', function(t) { + // have a length + var len = 16; + var list = [ 'foog', + 'bark', + 'bazy', + 'kuel' ]; + + // read more than the first element. + var ret = fromList(6, { buffer: list, length: 16, decoder: true }); + t.equal(ret, 'foogba'); + + // read exactly the first element. + ret = fromList(2, { buffer: list, length: 10, decoder: true }); + t.equal(ret, 'rk'); + + // read less than the first element. + ret = fromList(2, { buffer: list, length: 8, decoder: true }); + t.equal(ret, 'ba'); + + // read more than we have. + ret = fromList(100, { buffer: list, length: 6, decoder: true }); + t.equal(ret, 'zykuel'); + + // all consumed. + t.same(list, []); + + t.end(); +}); diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js new file mode 100644 index 000000000..117e253d2 --- /dev/null +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Stream = require('stream'); +var Readable = Stream.Readable; + +var r = new Readable(); +var N = 256; +var reads = 0; +r._read = function(n) { + return r.push(++reads === N ? null : new Buffer(1)); +}; + +var rended = false; +r.on('end', function() { + rended = true; +}); + +var w = new Stream(); +w.writable = true; +var writes = 0; +var buffered = 0; +w.write = function(c) { + writes += c.length; + buffered += c.length; + process.nextTick(drain); + return false; +}; + +function drain() { + assert(buffered <= 3); + buffered = 0; + w.emit('drain'); +} + + +var wended = false; +w.end = function() { + wended = true; +}; + +// Just for kicks, let's mess with the drain count. +// This verifies that even if it gets negative in the +// pipe() cleanup function, we'll still function properly. +r.on('readable', function() { + w.emit('drain'); +}); + +r.pipe(w); +process.on('exit', function() { + assert(rended); + assert(wended); + console.error('ok'); +}); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js new file mode 100644 index 000000000..65b7afda5 --- /dev/null +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common.js'); +var Readable = require('_stream_readable'); + +var len = 0; +var chunks = new Array(10); +for (var i = 1; i <= 10; i++) { + chunks[i-1] = new Buffer(i); + len += i; +} + +var test = new Readable(); +var n = 0; +test._read = function(size) { + var chunk = chunks[n++]; + setTimeout(function() { + test.push(chunk === undefined ? null : chunk); + }); +}; + +test.on('end', thrower); +function thrower() { + throw new Error('this should not happen!'); +} + +var bytesread = 0; +test.on('readable', function() { + var b = len - bytesread - 1; + var res = test.read(b); + if (res) { + bytesread += res.length; + console.error('br=%d len=%d', bytesread, len); + setTimeout(next); + } + test.read(0); +}); +test.read(0); + +function next() { + // now let's make 'end' happen + test.removeListener('end', thrower); + + var endEmitted = false; + process.on('exit', function() { + assert(endEmitted, 'end should be emitted by now'); + }); + test.on('end', function() { + endEmitted = true; + }); + + // one to get the last byte + var r = test.read(); + assert(r); + assert.equal(r.length, 1); + r = test.read(); + assert.equal(r, null); +} diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js new file mode 100644 index 000000000..2e5cf25c4 --- /dev/null +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -0,0 +1,43 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Readable = require('_stream_readable'); +var EE = require('events').EventEmitter; + +var oldStream = new EE(); +oldStream.pause = function(){}; +oldStream.resume = function(){}; + +var newStream = new Readable().wrap(oldStream); + +var ended = false; +newStream + .on('readable', function(){}) + .on('end', function(){ ended = true; }); + +oldStream.emit('end'); + +process.on('exit', function(){ + assert.ok(ended); +}); diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js new file mode 100644 index 000000000..293774ca5 --- /dev/null +++ b/test/parallel/test-stream2-readable-wrap.js @@ -0,0 +1,108 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var Readable = require('_stream_readable'); +var Writable = require('_stream_writable'); +var EE = require('events').EventEmitter; + +var testRuns = 0, completedRuns = 0; +function runTest(highWaterMark, objectMode, produce) { + testRuns++; + + var old = new EE; + var r = new Readable({ highWaterMark: highWaterMark, objectMode: objectMode }); + assert.equal(r, r.wrap(old)); + + var ended = false; + r.on('end', function() { + ended = true; + }); + + old.pause = function() { + console.error('old.pause()'); + old.emit('pause'); + flowing = false; + }; + + old.resume = function() { + console.error('old.resume()'); + old.emit('resume'); + flow(); + }; + + var flowing; + var chunks = 10; + var oldEnded = false; + var expected = []; + function flow() { + flowing = true; + while (flowing && chunks-- > 0) { + var item = produce(); + expected.push(item); + console.log('old.emit', chunks, flowing); + old.emit('data', item); + console.log('after emit', chunks, flowing); + } + if (chunks <= 0) { + oldEnded = true; + console.log('old end', chunks, flowing); + old.emit('end'); + } + } + + var w = new Writable({ highWaterMark: highWaterMark * 2, objectMode: objectMode }); + var written = []; + w._write = function(chunk, encoding, cb) { + console.log('_write', chunk); + written.push(chunk); + setTimeout(cb); + }; + + w.on('finish', function() { + completedRuns++; + performAsserts(); + }); + + r.pipe(w); + + flow(); + + function performAsserts() { + assert(ended); + assert(oldEnded); + assert.deepEqual(written, expected); + } +} + +runTest(100, false, function(){ return new Buffer(100); }); +runTest(10, false, function(){ return new Buffer('xxxxxxxxxx'); }); +runTest(1, true, function(){ return { foo: 'bar' }; }); + +var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; +runTest(1, true, function(){ return objectChunks.shift() }); + +process.on('exit', function() { + assert.equal(testRuns, completedRuns); + console.log('ok'); +}); diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js new file mode 100644 index 000000000..9b28e5594 --- /dev/null +++ b/test/parallel/test-stream2-set-encoding.js @@ -0,0 +1,367 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var assert = require('assert'); +var R = require('_stream_readable'); +var util = require('util'); + +// tiny node-tap lookalike. +var tests = []; +var count = 0; + +function test(name, fn) { + count++; + tests.push([name, fn]); +} + +function run() { + var next = tests.shift(); + if (!next) + return console.error('ok'); + + var name = next[0]; + var fn = next[1]; + console.log('# %s', name); + fn({ + same: assert.deepEqual, + equal: assert.equal, + end: function () { + count--; + run(); + } + }); +} + +// ensure all tests have run +process.on("exit", function () { + assert.equal(count, 0); +}); + +process.nextTick(run); + +///// + +util.inherits(TestReader, R); + +function TestReader(n, opts) { + R.call(this, opts); + + this.pos = 0; + this.len = n || 100; +} + +TestReader.prototype._read = function(n) { + setTimeout(function() { + + if (this.pos >= this.len) { + // double push(null) to test eos handling + this.push(null); + return this.push(null); + } + + n = Math.min(n, this.len - this.pos); + if (n <= 0) { + // double push(null) to test eos handling + this.push(null); + return this.push(null); + } + + this.pos += n; + var ret = new Buffer(n); + ret.fill('a'); + + console.log("this.push(ret)", ret) + + return this.push(ret); + }.bind(this), 1); +}; + +test('setEncoding utf8', function(t) { + var tr = new TestReader(100); + tr.setEncoding('utf8'); + var out = []; + var expect = + [ 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa' ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(10))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + + +test('setEncoding hex', function(t) { + var tr = new TestReader(100); + tr.setEncoding('hex'); + var out = []; + var expect = + [ '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161' ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(10))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + +test('setEncoding hex with read(13)', function(t) { + var tr = new TestReader(100); + tr.setEncoding('hex'); + var out = []; + var expect = + [ "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "16161" ]; + + tr.on('readable', function flow() { + console.log("readable once") + var chunk; + while (null !== (chunk = tr.read(13))) + out.push(chunk); + }); + + tr.on('end', function() { + console.log("END") + t.same(out, expect); + t.end(); + }); +}); + +test('setEncoding base64', function(t) { + var tr = new TestReader(100); + tr.setEncoding('base64'); + var out = []; + var expect = + [ 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYQ==' ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(10))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + +test('encoding: utf8', function(t) { + var tr = new TestReader(100, { encoding: 'utf8' }); + var out = []; + var expect = + [ 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa', + 'aaaaaaaaaa' ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(10))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + + +test('encoding: hex', function(t) { + var tr = new TestReader(100, { encoding: 'hex' }); + var out = []; + var expect = + [ '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161', + '6161616161' ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(10))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + +test('encoding: hex with read(13)', function(t) { + var tr = new TestReader(100, { encoding: 'hex' }); + var out = []; + var expect = + [ "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "1616161616161", + "6161616161616", + "16161" ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(13))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + +test('encoding: base64', function(t) { + var tr = new TestReader(100, { encoding: 'base64' }); + var out = []; + var expect = + [ 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYWFhYWFh', + 'YWFhYWFhYW', + 'FhYQ==' ]; + + tr.on('readable', function flow() { + var chunk; + while (null !== (chunk = tr.read(10))) + out.push(chunk); + }); + + tr.on('end', function() { + t.same(out, expect); + t.end(); + }); +}); + +test('chainable', function(t) { + var tr = new TestReader(100); + t.equal(tr.setEncoding('utf8'), tr); + t.end(); +}); diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js new file mode 100644 index 000000000..9c9ddd8ef --- /dev/null +++ b/test/parallel/test-stream2-transform.js @@ -0,0 +1,522 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common.js'); +var PassThrough = require('_stream_passthrough'); +var Transform = require('_stream_transform'); + +// tiny node-tap lookalike. +var tests = []; +var count = 0; + +function test(name, fn) { + count++; + tests.push([name, fn]); +} + +function run() { + var next = tests.shift(); + if (!next) + return console.error('ok'); + + var name = next[0]; + var fn = next[1]; + console.log('# %s', name); + fn({ + same: assert.deepEqual, + equal: assert.equal, + ok: assert, + end: function () { + count--; + run(); + } + }); +} + +// ensure all tests have run +process.on("exit", function () { + assert.equal(count, 0); +}); + +process.nextTick(run); + +///// + +test('writable side consumption', function(t) { + var tx = new Transform({ + highWaterMark: 10 + }); + + var transformed = 0; + tx._transform = function(chunk, encoding, cb) { + transformed += chunk.length; + tx.push(chunk); + cb(); + }; + + for (var i = 1; i <= 10; i++) { + tx.write(new Buffer(i)); + } + tx.end(); + + t.equal(tx._readableState.length, 10); + t.equal(transformed, 10); + t.equal(tx._transformState.writechunk.length, 5); + t.same(tx._writableState.buffer.map(function(c) { + return c.chunk.length; + }), [6, 7, 8, 9, 10]); + + t.end(); +}); + +test('passthrough', function(t) { + var pt = new PassThrough(); + + pt.write(new Buffer('foog')); + pt.write(new Buffer('bark')); + pt.write(new Buffer('bazy')); + pt.write(new Buffer('kuel')); + pt.end(); + + t.equal(pt.read(5).toString(), 'foogb'); + t.equal(pt.read(5).toString(), 'arkba'); + t.equal(pt.read(5).toString(), 'zykue'); + t.equal(pt.read(5).toString(), 'l'); + t.end(); +}); + +test('object passthrough', function (t) { + var pt = new PassThrough({ objectMode: true }); + + pt.write(1); + pt.write(true); + pt.write(false); + pt.write(0); + pt.write('foo'); + pt.write(''); + pt.write({ a: 'b'}); + pt.end(); + + t.equal(pt.read(), 1); + t.equal(pt.read(), true); + t.equal(pt.read(), false); + t.equal(pt.read(), 0); + t.equal(pt.read(), 'foo'); + t.equal(pt.read(), ''); + t.same(pt.read(), { a: 'b'}); + t.end(); +}); + +test('simple transform', function(t) { + var pt = new Transform; + pt._transform = function(c, e, cb) { + var ret = new Buffer(c.length); + ret.fill('x'); + pt.push(ret); + cb(); + }; + + pt.write(new Buffer('foog')); + pt.write(new Buffer('bark')); + pt.write(new Buffer('bazy')); + pt.write(new Buffer('kuel')); + pt.end(); + + t.equal(pt.read(5).toString(), 'xxxxx'); + t.equal(pt.read(5).toString(), 'xxxxx'); + t.equal(pt.read(5).toString(), 'xxxxx'); + t.equal(pt.read(5).toString(), 'x'); + t.end(); +}); + +test('simple object transform', function(t) { + var pt = new Transform({ objectMode: true }); + pt._transform = function(c, e, cb) { + pt.push(JSON.stringify(c)); + cb(); + }; + + pt.write(1); + pt.write(true); + pt.write(false); + pt.write(0); + pt.write('foo'); + pt.write(''); + pt.write({ a: 'b'}); + pt.end(); + + t.equal(pt.read(), '1'); + t.equal(pt.read(), 'true'); + t.equal(pt.read(), 'false'); + t.equal(pt.read(), '0'); + t.equal(pt.read(), '"foo"'); + t.equal(pt.read(), '""'); + t.equal(pt.read(), '{"a":"b"}'); + t.end(); +}); + +test('async passthrough', function(t) { + var pt = new Transform; + pt._transform = function(chunk, encoding, cb) { + setTimeout(function() { + pt.push(chunk); + cb(); + }, 10); + }; + + pt.write(new Buffer('foog')); + pt.write(new Buffer('bark')); + pt.write(new Buffer('bazy')); + pt.write(new Buffer('kuel')); + pt.end(); + + pt.on('finish', function() { + t.equal(pt.read(5).toString(), 'foogb'); + t.equal(pt.read(5).toString(), 'arkba'); + t.equal(pt.read(5).toString(), 'zykue'); + t.equal(pt.read(5).toString(), 'l'); + t.end(); + }); +}); + +test('assymetric transform (expand)', function(t) { + var pt = new Transform; + + // emit each chunk 2 times. + pt._transform = function(chunk, encoding, cb) { + setTimeout(function() { + pt.push(chunk); + setTimeout(function() { + pt.push(chunk); + cb(); + }, 10) + }, 10); + }; + + pt.write(new Buffer('foog')); + pt.write(new Buffer('bark')); + pt.write(new Buffer('bazy')); + pt.write(new Buffer('kuel')); + pt.end(); + + pt.on('finish', function() { + t.equal(pt.read(5).toString(), 'foogf'); + t.equal(pt.read(5).toString(), 'oogba'); + t.equal(pt.read(5).toString(), 'rkbar'); + t.equal(pt.read(5).toString(), 'kbazy'); + t.equal(pt.read(5).toString(), 'bazyk'); + t.equal(pt.read(5).toString(), 'uelku'); + t.equal(pt.read(5).toString(), 'el'); + t.end(); + }); +}); + +test('assymetric transform (compress)', function(t) { + var pt = new Transform; + + // each output is the first char of 3 consecutive chunks, + // or whatever's left. + pt.state = ''; + + pt._transform = function(chunk, encoding, cb) { + if (!chunk) + chunk = ''; + var s = chunk.toString(); + setTimeout(function() { + this.state += s.charAt(0); + if (this.state.length === 3) { + pt.push(new Buffer(this.state)); + this.state = ''; + } + cb(); + }.bind(this), 10); + }; + + pt._flush = function(cb) { + // just output whatever we have. + pt.push(new Buffer(this.state)); + this.state = ''; + cb(); + }; + + pt.write(new Buffer('aaaa')); + pt.write(new Buffer('bbbb')); + pt.write(new Buffer('cccc')); + pt.write(new Buffer('dddd')); + pt.write(new Buffer('eeee')); + pt.write(new Buffer('aaaa')); + pt.write(new Buffer('bbbb')); + pt.write(new Buffer('cccc')); + pt.write(new Buffer('dddd')); + pt.write(new Buffer('eeee')); + pt.write(new Buffer('aaaa')); + pt.write(new Buffer('bbbb')); + pt.write(new Buffer('cccc')); + pt.write(new Buffer('dddd')); + pt.end(); + + // 'abcdeabcdeabcd' + pt.on('finish', function() { + t.equal(pt.read(5).toString(), 'abcde'); + t.equal(pt.read(5).toString(), 'abcde'); + t.equal(pt.read(5).toString(), 'abcd'); + t.end(); + }); +}); + +// this tests for a stall when data is written to a full stream +// that has empty transforms. +test('complex transform', function(t) { + var count = 0; + var saved = null; + var pt = new Transform({highWaterMark:3}); + pt._transform = function(c, e, cb) { + if (count++ === 1) + saved = c; + else { + if (saved) { + pt.push(saved); + saved = null; + } + pt.push(c); + } + + cb(); + }; + + pt.once('readable', function() { + process.nextTick(function() { + pt.write(new Buffer('d')); + pt.write(new Buffer('ef'), function() { + pt.end(); + t.end(); + }); + t.equal(pt.read().toString(), 'abcdef'); + t.equal(pt.read(), null); + }); + }); + + pt.write(new Buffer('abc')); +}); + + +test('passthrough event emission', function(t) { + var pt = new PassThrough(); + var emits = 0; + pt.on('readable', function() { + var state = pt._readableState; + console.error('>>> emit readable %d', emits); + emits++; + }); + + var i = 0; + + pt.write(new Buffer('foog')); + + console.error('need emit 0'); + pt.write(new Buffer('bark')); + + console.error('should have emitted readable now 1 === %d', emits); + t.equal(emits, 1); + + t.equal(pt.read(5).toString(), 'foogb'); + t.equal(pt.read(5) + '', 'null'); + + console.error('need emit 1'); + + pt.write(new Buffer('bazy')); + console.error('should have emitted, but not again'); + pt.write(new Buffer('kuel')); + + console.error('should have emitted readable now 2 === %d', emits); + t.equal(emits, 2); + + t.equal(pt.read(5).toString(), 'arkba'); + t.equal(pt.read(5).toString(), 'zykue'); + t.equal(pt.read(5), null); + + console.error('need emit 2'); + + pt.end(); + + t.equal(emits, 3); + + t.equal(pt.read(5).toString(), 'l'); + t.equal(pt.read(5), null); + + console.error('should not have emitted again'); + t.equal(emits, 3); + t.end(); +}); + +test('passthrough event emission reordered', function(t) { + var pt = new PassThrough; + var emits = 0; + pt.on('readable', function() { + console.error('emit readable', emits) + emits++; + }); + + pt.write(new Buffer('foog')); + console.error('need emit 0'); + pt.write(new Buffer('bark')); + console.error('should have emitted readable now 1 === %d', emits); + t.equal(emits, 1); + + t.equal(pt.read(5).toString(), 'foogb'); + t.equal(pt.read(5), null); + + console.error('need emit 1'); + pt.once('readable', function() { + t.equal(pt.read(5).toString(), 'arkba'); + + t.equal(pt.read(5), null); + + console.error('need emit 2'); + pt.once('readable', function() { + t.equal(pt.read(5).toString(), 'zykue'); + t.equal(pt.read(5), null); + pt.once('readable', function() { + t.equal(pt.read(5).toString(), 'l'); + t.equal(pt.read(5), null); + t.equal(emits, 4); + t.end(); + }); + pt.end(); + }); + pt.write(new Buffer('kuel')); + }); + + pt.write(new Buffer('bazy')); +}); + +test('passthrough facaded', function(t) { + console.error('passthrough facaded'); + var pt = new PassThrough; + var datas = []; + pt.on('data', function(chunk) { + datas.push(chunk.toString()); + }); + + pt.on('end', function() { + t.same(datas, ['foog', 'bark', 'bazy', 'kuel']); + t.end(); + }); + + pt.write(new Buffer('foog')); + setTimeout(function() { + pt.write(new Buffer('bark')); + setTimeout(function() { + pt.write(new Buffer('bazy')); + setTimeout(function() { + pt.write(new Buffer('kuel')); + setTimeout(function() { + pt.end(); + }, 10); + }, 10); + }, 10); + }, 10); +}); + +test('object transform (json parse)', function(t) { + console.error('json parse stream'); + var jp = new Transform({ objectMode: true }); + jp._transform = function(data, encoding, cb) { + try { + jp.push(JSON.parse(data)); + cb(); + } catch (er) { + cb(er); + } + }; + + // anything except null/undefined is fine. + // those are "magic" in the stream API, because they signal EOF. + var objects = [ + { foo: 'bar' }, + 100, + "string", + { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } + ]; + + var ended = false; + jp.on('end', function() { + ended = true; + }); + + objects.forEach(function(obj) { + jp.write(JSON.stringify(obj)); + var res = jp.read(); + t.same(res, obj); + }); + + jp.end(); + // read one more time to get the 'end' event + jp.read(); + + process.nextTick(function() { + t.ok(ended); + t.end(); + }) +}); + +test('object transform (json stringify)', function(t) { + console.error('json parse stream'); + var js = new Transform({ objectMode: true }); + js._transform = function(data, encoding, cb) { + try { + js.push(JSON.stringify(data)); + cb(); + } catch (er) { + cb(er); + } + }; + + // anything except null/undefined is fine. + // those are "magic" in the stream API, because they signal EOF. + var objects = [ + { foo: 'bar' }, + 100, + "string", + { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } + ]; + + var ended = false; + js.on('end', function() { + ended = true; + }); + + objects.forEach(function(obj) { + js.write(obj); + var res = js.read(); + t.equal(res, JSON.stringify(obj)); + }); + + js.end(); + // read one more time to get the 'end' event + js.read(); + + process.nextTick(function() { + t.ok(ended); + t.end(); + }) +}); diff --git a/test/parallel/test-stream2-unpipe-drain.js b/test/parallel/test-stream2-unpipe-drain.js new file mode 100644 index 000000000..d66dc3cbe --- /dev/null +++ b/test/parallel/test-stream2-unpipe-drain.js @@ -0,0 +1,76 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var assert = require('assert'); +var stream = require('stream'); +var crypto = require('crypto'); + +var util = require('util'); + +function TestWriter() { + stream.Writable.call(this); +} +util.inherits(TestWriter, stream.Writable); + +TestWriter.prototype._write = function (buffer, encoding, callback) { + console.log('write called'); + // super slow write stream (callback never called) +}; + +var dest = new TestWriter(); + +function TestReader(id) { + stream.Readable.call(this); + this.reads = 0; +} +util.inherits(TestReader, stream.Readable); + +TestReader.prototype._read = function (size) { + this.reads += 1; + this.push(crypto.randomBytes(size)); +}; + +var src1 = new TestReader(); +var src2 = new TestReader(); + +src1.pipe(dest); + +src1.once('readable', function () { + process.nextTick(function () { + + src2.pipe(dest); + + src2.once('readable', function () { + process.nextTick(function () { + + src1.unpipe(dest); + }); + }); + }); +}); + + +process.on('exit', function () { + assert.equal(src1.reads, 2); + assert.equal(src2.reads, 2); +}); diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js new file mode 100644 index 000000000..99f8746c4 --- /dev/null +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var assert = require('assert'); +var stream = require('stream'); + +var chunk = new Buffer('hallo'); + +var util = require('util'); + +function TestWriter() { + stream.Writable.call(this); +} +util.inherits(TestWriter, stream.Writable); + +TestWriter.prototype._write = function(buffer, encoding, callback) { + callback(null); +}; + +var dest = new TestWriter(); + +// Set this high so that we'd trigger a nextTick warning +// and/or RangeError if we do maybeReadMore wrong. +function TestReader() { + stream.Readable.call(this, { highWaterMark: 0x10000 }); +} +util.inherits(TestReader, stream.Readable); + +TestReader.prototype._read = function(size) { + this.push(chunk); +}; + +var src = new TestReader(); + +for (var i = 0; i < 10; i++) { + src.pipe(dest); + src.unpipe(dest); +} + +assert.equal(src.listeners('end').length, 0); +assert.equal(src.listeners('readable').length, 0); + +assert.equal(dest.listeners('unpipe').length, 0); +assert.equal(dest.listeners('drain').length, 0); +assert.equal(dest.listeners('error').length, 0); +assert.equal(dest.listeners('close').length, 0); +assert.equal(dest.listeners('finish').length, 0); + +console.error(src._readableState); +process.on('exit', function() { + src._readableState.buffer.length = 0; + console.error(src._readableState); + assert(src._readableState.length >= src._readableState.highWaterMark); + console.log('ok'); +}); diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js new file mode 100644 index 000000000..3767ce140 --- /dev/null +++ b/test/parallel/test-stream2-writable.js @@ -0,0 +1,405 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var W = require('_stream_writable'); +var D = require('_stream_duplex'); +var assert = require('assert'); + +var util = require('util'); +util.inherits(TestWriter, W); + +function TestWriter() { + W.apply(this, arguments); + this.buffer = []; + this.written = 0; +} + +TestWriter.prototype._write = function(chunk, encoding, cb) { + // simulate a small unpredictable latency + setTimeout(function() { + this.buffer.push(chunk.toString()); + this.written += chunk.length; + cb(); + }.bind(this), Math.floor(Math.random() * 10)); +}; + +var chunks = new Array(50); +for (var i = 0; i < chunks.length; i++) { + chunks[i] = new Array(i + 1).join('x'); +} + +// tiny node-tap lookalike. +var tests = []; +var count = 0; + +function test(name, fn) { + count++; + tests.push([name, fn]); +} + +function run() { + var next = tests.shift(); + if (!next) + return console.error('ok'); + + var name = next[0]; + var fn = next[1]; + console.log('# %s', name); + fn({ + same: assert.deepEqual, + equal: assert.equal, + end: function () { + count--; + run(); + } + }); +} + +// ensure all tests have run +process.on("exit", function () { + assert.equal(count, 0); +}); + +process.nextTick(run); + +test('write fast', function(t) { + var tw = new TestWriter({ + highWaterMark: 100 + }); + + tw.on('finish', function() { + t.same(tw.buffer, chunks, 'got chunks in the right order'); + t.end(); + }); + + chunks.forEach(function(chunk) { + // screw backpressure. Just buffer it all up. + tw.write(chunk); + }); + tw.end(); +}); + +test('write slow', function(t) { + var tw = new TestWriter({ + highWaterMark: 100 + }); + + tw.on('finish', function() { + t.same(tw.buffer, chunks, 'got chunks in the right order'); + t.end(); + }); + + var i = 0; + (function W() { + tw.write(chunks[i++]); + if (i < chunks.length) + setTimeout(W, 10); + else + tw.end(); + })(); +}); + +test('write backpressure', function(t) { + var tw = new TestWriter({ + highWaterMark: 50 + }); + + var drains = 0; + + tw.on('finish', function() { + t.same(tw.buffer, chunks, 'got chunks in the right order'); + t.equal(drains, 17); + t.end(); + }); + + tw.on('drain', function() { + drains++; + }); + + var i = 0; + (function W() { + do { + var ret = tw.write(chunks[i++]); + } while (ret !== false && i < chunks.length); + + if (i < chunks.length) { + assert(tw._writableState.length >= 50); + tw.once('drain', W); + } else { + tw.end(); + } + })(); +}); + +test('write bufferize', function(t) { + var tw = new TestWriter({ + highWaterMark: 100 + }); + + var encodings = + [ 'hex', + 'utf8', + 'utf-8', + 'ascii', + 'binary', + 'base64', + 'ucs2', + 'ucs-2', + 'utf16le', + 'utf-16le', + undefined ]; + + tw.on('finish', function() { + t.same(tw.buffer, chunks, 'got the expected chunks'); + }); + + chunks.forEach(function(chunk, i) { + var enc = encodings[ i % encodings.length ]; + chunk = new Buffer(chunk); + tw.write(chunk.toString(enc), enc); + }); + t.end(); +}); + +test('write no bufferize', function(t) { + var tw = new TestWriter({ + highWaterMark: 100, + decodeStrings: false + }); + + tw._write = function(chunk, encoding, cb) { + assert(typeof chunk === 'string'); + chunk = new Buffer(chunk, encoding); + return TestWriter.prototype._write.call(this, chunk, encoding, cb); + }; + + var encodings = + [ 'hex', + 'utf8', + 'utf-8', + 'ascii', + 'binary', + 'base64', + 'ucs2', + 'ucs-2', + 'utf16le', + 'utf-16le', + undefined ]; + + tw.on('finish', function() { + t.same(tw.buffer, chunks, 'got the expected chunks'); + }); + + chunks.forEach(function(chunk, i) { + var enc = encodings[ i % encodings.length ]; + chunk = new Buffer(chunk); + tw.write(chunk.toString(enc), enc); + }); + t.end(); +}); + +test('write callbacks', function (t) { + var callbacks = chunks.map(function(chunk, i) { + return [i, function(er) { + callbacks._called[i] = chunk; + }]; + }).reduce(function(set, x) { + set['callback-' + x[0]] = x[1]; + return set; + }, {}); + callbacks._called = []; + + var tw = new TestWriter({ + highWaterMark: 100 + }); + + tw.on('finish', function() { + process.nextTick(function() { + t.same(tw.buffer, chunks, 'got chunks in the right order'); + t.same(callbacks._called, chunks, 'called all callbacks'); + t.end(); + }); + }); + + chunks.forEach(function(chunk, i) { + tw.write(chunk, callbacks['callback-' + i]); + }); + tw.end(); +}); + +test('end callback', function (t) { + var tw = new TestWriter(); + tw.end(function () { + t.end(); + }); +}); + +test('end callback with chunk', function (t) { + var tw = new TestWriter(); + tw.end(new Buffer('hello world'), function () { + t.end(); + }); +}); + +test('end callback with chunk and encoding', function (t) { + var tw = new TestWriter(); + tw.end('hello world', 'ascii', function () { + t.end(); + }); +}); + +test('end callback after .write() call', function (t) { + var tw = new TestWriter(); + tw.write(new Buffer('hello world')); + tw.end(function () { + t.end(); + }); +}); + +test('end callback called after write callback', function (t) { + var tw = new TestWriter(); + var writeCalledback = false; + tw.write(new Buffer('hello world'), function() { + writeCalledback = true; + }); + tw.end(function () { + t.equal(writeCalledback, true); + t.end(); + }); +}); + +test('encoding should be ignored for buffers', function(t) { + var tw = new W(); + var hex = '018b5e9a8f6236ffe30e31baf80d2cf6eb'; + tw._write = function(chunk, encoding, cb) { + t.equal(chunk.toString('hex'), hex); + t.end(); + }; + var buf = new Buffer(hex, 'hex'); + tw.write(buf, 'binary'); +}); + +test('writables are not pipable', function(t) { + var w = new W(); + w._write = function() {}; + var gotError = false; + w.on('error', function(er) { + gotError = true; + }); + w.pipe(process.stdout); + assert(gotError); + t.end(); +}); + +test('duplexes are pipable', function(t) { + var d = new D(); + d._read = function() {}; + d._write = function() {}; + var gotError = false; + d.on('error', function(er) { + gotError = true; + }); + d.pipe(process.stdout); + assert(!gotError); + t.end(); +}); + +test('end(chunk) two times is an error', function(t) { + var w = new W(); + w._write = function() {}; + var gotError = false; + w.on('error', function(er) { + gotError = true; + t.equal(er.message, 'write after end'); + }); + w.end('this is the end'); + w.end('and so is this'); + process.nextTick(function() { + assert(gotError); + t.end(); + }); +}); + +test('dont end while writing', function(t) { + var w = new W(); + var wrote = false; + w._write = function(chunk, e, cb) { + assert(!this.writing); + wrote = true; + this.writing = true; + setTimeout(function() { + this.writing = false; + cb(); + }); + }; + w.on('finish', function() { + assert(wrote); + t.end(); + }); + w.write(Buffer(0)); + w.end(); +}); + +test('finish does not come before write cb', function(t) { + var w = new W(); + var writeCb = false; + w._write = function(chunk, e, cb) { + setTimeout(function() { + writeCb = true; + cb(); + }, 10); + }; + w.on('finish', function() { + assert(writeCb); + t.end(); + }); + w.write(Buffer(0)); + w.end(); +}); + +test('finish does not come before sync _write cb', function(t) { + var w = new W(); + var writeCb = false; + w._write = function(chunk, e, cb) { + cb(); + }; + w.on('finish', function() { + assert(writeCb); + t.end(); + }); + w.write(Buffer(0), function(er) { + writeCb = true; + }); + w.end(); +}); + +test('finish is emitted if last chunk is empty', function(t) { + var w = new W(); + w._write = function(chunk, e, cb) { + process.nextTick(cb); + }; + w.on('finish', function() { + t.end(); + }); + w.write(Buffer(1)); + w.end(Buffer(0)); +}); diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js new file mode 100644 index 000000000..b91bde3f0 --- /dev/null +++ b/test/parallel/test-stream3-pause-then-read.js @@ -0,0 +1,167 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var stream = require('stream'); +var Readable = stream.Readable; +var Writable = stream.Writable; + +var totalChunks = 100; +var chunkSize = 99; +var expectTotalData = totalChunks * chunkSize; +var expectEndingData = expectTotalData; + +var r = new Readable({ highWaterMark: 1000 }); +var chunks = totalChunks; +r._read = function(n) { + if (!(chunks % 2)) + setImmediate(push); + else if (!(chunks % 3)) + process.nextTick(push); + else + push(); +}; + +var totalPushed = 0; +function push() { + var chunk = chunks-- > 0 ? new Buffer(chunkSize) : null; + if (chunk) { + totalPushed += chunk.length; + chunk.fill('x'); + } + r.push(chunk); +} + +read100(); + +// first we read 100 bytes +function read100() { + readn(100, onData); +} + +function readn(n, then) { + console.error('read %d', n); + expectEndingData -= n; + ;(function read() { + var c = r.read(n); + if (!c) + r.once('readable', read); + else { + assert.equal(c.length, n); + assert(!r._readableState.flowing); + then(); + } + })(); +} + +// then we listen to some data events +function onData() { + expectEndingData -= 100; + console.error('onData'); + var seen = 0; + r.on('data', function od(c) { + seen += c.length; + if (seen >= 100) { + // seen enough + r.removeListener('data', od); + r.pause(); + if (seen > 100) { + // oh no, seen too much! + // put the extra back. + var diff = seen - 100; + r.unshift(c.slice(c.length - diff)); + console.error('seen too much', seen, diff); + } + + // Nothing should be lost in between + setImmediate(pipeLittle); + } + }); +} + +// Just pipe 200 bytes, then unshift the extra and unpipe +function pipeLittle() { + expectEndingData -= 200; + console.error('pipe a little'); + var w = new Writable(); + var written = 0; + w.on('finish', function() { + assert.equal(written, 200); + setImmediate(read1234); + }); + w._write = function(chunk, encoding, cb) { + written += chunk.length; + if (written >= 200) { + r.unpipe(w); + w.end(); + cb(); + if (written > 200) { + var diff = written - 200; + written -= diff; + r.unshift(chunk.slice(chunk.length - diff)); + } + } else { + setImmediate(cb); + } + }; + r.pipe(w); +} + +// now read 1234 more bytes +function read1234() { + readn(1234, resumePause); +} + +function resumePause() { + console.error('resumePause'); + // don't read anything, just resume and re-pause a whole bunch + r.resume(); + r.pause(); + r.resume(); + r.pause(); + r.resume(); + r.pause(); + r.resume(); + r.pause(); + r.resume(); + r.pause(); + setImmediate(pipe); +} + + +function pipe() { + console.error('pipe the rest'); + var w = new Writable(); + var written = 0; + w._write = function(chunk, encoding, cb) { + written += chunk.length; + cb(); + }; + w.on('finish', function() { + console.error('written', written, totalPushed); + assert.equal(written, expectEndingData); + assert.equal(totalPushed, expectTotalData); + console.log('ok'); + }); + r.pipe(w); +} diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js new file mode 100644 index 000000000..fea55d410 --- /dev/null +++ b/test/parallel/test-string-decoder-end.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// verify that the string decoder works getting 1 byte at a time, +// the whole buffer at once, and that both match the .toString(enc) +// result of the entire buffer. + +var assert = require('assert'); +var SD = require('string_decoder').StringDecoder; +var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; + +var bufs = [ '☃💩', 'asdf' ].map(function(b) { + return new Buffer(b); +}); + +// also test just arbitrary bytes from 0-15. +for (var i = 1; i <= 16; i++) { + var bytes = new Array(i).join('.').split('.').map(function(_, j) { + return j + 0x78; + }); + bufs.push(new Buffer(bytes)); +} + +encodings.forEach(testEncoding); + +console.log('ok'); + +function testEncoding(encoding) { + bufs.forEach(function(buf) { + testBuf(encoding, buf); + }); +} + +function testBuf(encoding, buf) { + console.error('# %s', encoding, buf); + + // write one byte at a time. + var s = new SD(encoding); + var res1 = ''; + for (var i = 0; i < buf.length; i++) { + res1 += s.write(buf.slice(i, i + 1)); + } + res1 += s.end(); + + // write the whole buffer at once. + var res2 = ''; + var s = new SD(encoding); + res2 += s.write(buf); + res2 += s.end(); + + // .toString() on the buffer + var res3 = buf.toString(encoding); + + console.log('expect=%j', res3); + assert.equal(res1, res3, 'one byte at a time should match toString'); + assert.equal(res2, res3, 'all bytes at once should match toString'); +} diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js new file mode 100644 index 000000000..9f47d131b --- /dev/null +++ b/test/parallel/test-string-decoder.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var StringDecoder = require('string_decoder').StringDecoder; + +process.stdout.write('scanning '); + +// UTF-8 +test('utf-8', new Buffer('$', 'utf-8'), '$'); +test('utf-8', new Buffer('¢', 'utf-8'), '¢'); +test('utf-8', new Buffer('€', 'utf-8'), '€'); +test('utf-8', new Buffer('𤭢', 'utf-8'), '𤭢'); +// A mixed ascii and non-ascii string +// Test stolen from deps/v8/test/cctest/test-strings.cc +// U+02E4 -> CB A4 +// U+0064 -> 64 +// U+12E4 -> E1 8B A4 +// U+0030 -> 30 +// U+3045 -> E3 81 85 +test( + 'utf-8', + new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), + '\u02e4\u0064\u12e4\u0030\u3045' +); + +// CESU-8 +test('utf-8', new Buffer('EDA0BDEDB18D', 'hex'), '\ud83d\udc4d'); // thumbs up + +// UCS-2 +test('ucs2', new Buffer('ababc', 'ucs2'), 'ababc'); + +// UTF-16LE +test('ucs2', new Buffer('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up + +console.log(' crayon!'); + +// test verifies that StringDecoder will correctly decode the given input +// buffer with the given encoding to the expected output. It will attempt all +// possible ways to write() the input buffer, see writeSequences(). The +// singleSequence allows for easy debugging of a specific sequence which is +// useful in case of test failures. +function test(encoding, input, expected, singleSequence) { + var sequences; + if (!singleSequence) { + sequences = writeSequences(input.length); + } else { + sequences = [singleSequence]; + } + sequences.forEach(function(sequence) { + var decoder = new StringDecoder(encoding); + var output = ''; + sequence.forEach(function(write) { + output += decoder.write(input.slice(write[0], write[1])); + }); + process.stdout.write('.'); + if (output !== expected) { + var message = + 'Expected "'+unicodeEscape(expected)+'", '+ + 'but got "'+unicodeEscape(output)+'"\n'+ + 'Write sequence: '+JSON.stringify(sequence)+'\n'+ + 'Decoder charBuffer: 0x'+decoder.charBuffer.toString('hex')+'\n'+ + 'Full Decoder State: '+JSON.stringify(decoder, null, 2); + assert.fail(output, expected, message); + } + }); +} + +// unicodeEscape prints the str contents as unicode escape codes. +function unicodeEscape(str) { + var r = ''; + for (var i = 0; i < str.length; i++) { + r += '\\u'+str.charCodeAt(i).toString(16); + } + return r; +} + +// writeSequences returns an array of arrays that describes all possible ways a +// buffer of the given length could be split up and passed to sequential write +// calls. +// +// e.G. writeSequences(3) will return: [ +// [ [ 0, 3 ] ], +// [ [ 0, 2 ], [ 2, 3 ] ], +// [ [ 0, 1 ], [ 1, 3 ] ], +// [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ] +// ] +function writeSequences(length, start, sequence) { + if (start === undefined) { + start = 0; + sequence = [] + } else if (start === length) { + return [sequence]; + } + var sequences = []; + for (var end = length; end > start; end--) { + var subSequence = sequence.concat([[start, end]]); + var subSequences = writeSequences(length, end, subSequence, sequences); + sequences = sequences.concat(subSequences); + } + return sequences; +} + diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js new file mode 100644 index 000000000..c7c716c83 --- /dev/null +++ b/test/parallel/test-stringbytes-external.js @@ -0,0 +1,134 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +// minimum string size to overflow into external string space +var EXTERN_APEX = 0xFBEE9; + +// manually controlled string for checking binary output +var ucs2_control = 'a\u0000'; +var write_str = 'a'; + + +// first do basic checks +var b = new Buffer(write_str, 'ucs2'); +var c = b.toString('binary'); +assert.equal(b[0], 0x61); +assert.equal(b[1], 0); +assert.equal(ucs2_control, c); + + +// grow the strings to proper length +while (write_str.length <= EXTERN_APEX) { + write_str += write_str; + ucs2_control += ucs2_control; +} +write_str += write_str.substr(0, EXTERN_APEX - write_str.length); +ucs2_control += ucs2_control.substr(0, EXTERN_APEX * 2 - ucs2_control.length); + + +// check resultant buffer and output string +var b = new Buffer(write_str, 'ucs2'); +// check fist Buffer created from write string +for (var i = 0; i < b.length; i += 2) { + assert.equal(b[i], 0x61); + assert.equal(b[i + 1], 0); +} +// create another string to create an external string +var b_bin = b.toString('binary'); +var b_ucs = b.toString('ucs2'); +// check control against external binary string +assert.equal(ucs2_control, b_bin); +// create buffer copy from external +var c_bin = new Buffer(b_bin, 'binary'); +var c_ucs = new Buffer(b_ucs, 'ucs2'); +// make sure they're the same length +assert.equal(c_bin.length, c_ucs.length); +// make sure Buffers from externals are the same +for (var i = 0; i < c_bin.length; i++) { + assert.equal(c_bin[i], c_ucs[i], c_bin[i] + ' == ' + c_ucs[i] + + ' : index ' + i); +} +// check resultant strings +assert.equal(c_bin.toString('ucs2'), c_ucs.toString('ucs2')); +assert.equal(c_bin.toString('binary'), ucs2_control); +assert.equal(c_ucs.toString('binary'), ucs2_control); + + + +// now let's test BASE64 and HEX ecoding/decoding +var RADIOS = 2; +var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; +var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; + +(function () { + for (var j = 0; j < RADIOS * 2; j += 1) { + var datum = b; + var slice = datum.slice(0, PRE_HALF_APEX + j); + var slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); + var pumped_string = slice.toString('hex'); + var pumped_string2 = slice2.toString('hex'); + var decoded = new Buffer(pumped_string, 'hex'); + + var metadata = "\nEXTERN_APEX=1031913 - pumped_string.length=" + metadata += pumped_string.length + '\n'; + + // the string are the same? + for (var k = 0; k < pumped_string.length; ++k) { + assert.equal(pumped_string[k], pumped_string2[k], + metadata + 'chars should be the same at ' + k); + } + + // the recoded buffer is the same? + for (var i = 0; i < decoded.length; ++i) { + assert.equal(datum[i], decoded[i], + metadata + 'bytes should be the same at ' + i); + } + } +})(); + +(function () { + for (var j = 0; j < RADIOS * 2; j += 1) { + var datum = b; + var slice = datum.slice(0, PRE_3OF4_APEX + j); + var slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); + var pumped_string = slice.toString('base64'); + var pumped_string2 = slice2.toString('base64'); + var decoded = new Buffer(pumped_string, 'base64'); + + var metadata = "\nEXTERN_APEX=1031913 - data=" + slice.length + metadata += " pumped_string.length=" + pumped_string.length + '\n'; + + // the string are the same? + for (var k = 0; k < pumped_string.length - 3; ++k) { + assert.equal(pumped_string[k], pumped_string2[k], + metadata + 'chars should be the same for two slices at ' + + k + ' ' + pumped_string[k] + ' ' + pumped_string2[k]); + } + + // the recoded buffer is the same? + for (var i = 0; i < decoded.length; ++i) { + assert.equal(datum[i], decoded[i], + metadata + 'bytes should be the same at ' + i); + } + } +})(); diff --git a/test/parallel/test-sys.js b/test/parallel/test-sys.js new file mode 100644 index 000000000..6ea33161c --- /dev/null +++ b/test/parallel/test-sys.js @@ -0,0 +1,129 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +assert.equal('0', common.inspect(0)); +assert.equal('1', common.inspect(1)); +assert.equal('false', common.inspect(false)); +assert.equal("''", common.inspect('')); +assert.equal("'hello'", common.inspect('hello')); +assert.equal('[Function]', common.inspect(function() {})); +assert.equal('undefined', common.inspect(undefined)); +assert.equal('null', common.inspect(null)); +assert.equal('/foo(bar\\n)?/gi', common.inspect(/foo(bar\n)?/gi)); +assert.equal(new Date('2010-02-14T12:48:40+01:00').toString(), + common.inspect(new Date('Sun, 14 Feb 2010 11:48:40 GMT'))); + +assert.equal("'\\n\\u0001'", common.inspect('\n\u0001')); + +assert.equal('[]', common.inspect([])); +assert.equal('{}', common.inspect(Object.create([]))); +assert.equal('[ 1, 2 ]', common.inspect([1, 2])); +assert.equal('[ 1, [ 2, 3 ] ]', common.inspect([1, [2, 3]])); + +assert.equal('{}', common.inspect({})); +assert.equal('{ a: 1 }', common.inspect({a: 1})); +assert.equal('{ a: [Function] }', common.inspect({a: function() {}})); +assert.equal('{ a: 1, b: 2 }', common.inspect({a: 1, b: 2})); +assert.equal('{ a: {} }', common.inspect({'a': {}})); +assert.equal('{ a: { b: 2 } }', common.inspect({'a': {'b': 2}})); +assert.equal('{ a: { b: { c: [Object] } } }', + common.inspect({'a': {'b': { 'c': { 'd': 2 }}}})); +assert.equal('{ a: { b: { c: { d: 2 } } } }', + common.inspect({'a': {'b': { 'c': { 'd': 2 }}}}, false, null)); +assert.equal('[ 1, 2, 3, [length]: 3 ]', common.inspect([1, 2, 3], true)); +assert.equal('{ a: [Object] }', + common.inspect({'a': {'b': { 'c': 2}}}, false, 0)); +assert.equal('{ a: { b: [Object] } }', + common.inspect({'a': {'b': { 'c': 2}}}, false, 1)); +assert.equal('{ visible: 1 }', + common.inspect(Object.create({}, + {visible: {value: 1, enumerable: true}, hidden: {value: 2}})) +); + +// Due to the hash seed randomization it's not deterministic the order that +// the following ways this hash is displayed. +// See http://codereview.chromium.org/9124004/ + +var out = common.inspect(Object.create({}, + {visible: {value: 1, enumerable: true}, hidden: {value: 2}}), true); +if (out !== '{ [hidden]: 2, visible: 1 }' && + out !== '{ visible: 1, [hidden]: 2 }') { + assert.ok(false); +} + + +// Objects without prototype +var out = common.inspect(Object.create(null, + { name: {value: 'Tim', enumerable: true}, + hidden: {value: 'secret'}}), true); +if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && + out !== "{ name: 'Tim', [hidden]: 'secret' }") { + assert(false); +} + + +assert.equal('{ name: \'Tim\' }', + common.inspect(Object.create(null, + {name: {value: 'Tim', enumerable: true}, + hidden: {value: 'secret'}})) +); + + +// Dynamic properties +assert.equal('{ readonly: [Getter] }', + common.inspect({get readonly() {}})); + +assert.equal('{ readwrite: [Getter/Setter] }', + common.inspect({get readwrite() {},set readwrite(val) {}})); + +assert.equal('{ writeonly: [Setter] }', + common.inspect({set writeonly(val) {}})); + +var value = {}; +value['a'] = value; +assert.equal('{ a: [Circular] }', common.inspect(value)); + +// Array with dynamic properties +value = [1, 2, 3]; +value.__defineGetter__('growingLength', function() { + this.push(true); return this.length; +}); +assert.equal('[ 1, 2, 3, growingLength: [Getter] ]', common.inspect(value)); + +// Function with properties +value = function() {}; +value.aprop = 42; +assert.equal('{ [Function] aprop: 42 }', common.inspect(value)); + +// Regular expressions with properties +value = /123/ig; +value.aprop = 42; +assert.equal('{ /123/gi aprop: 42 }', common.inspect(value)); + +// Dates with properties +value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); +value.aprop = 42; +assert.equal('{ Sun, 14 Feb 2010 11:48:40 GMT aprop: 42 }', + common.inspect(value) +); diff --git a/test/parallel/test-tcp-wrap.js b/test/parallel/test-tcp-wrap.js new file mode 100644 index 000000000..bc1e14e68 --- /dev/null +++ b/test/parallel/test-tcp-wrap.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TCP = process.binding('tcp_wrap').TCP; +var uv = process.binding('uv'); + +var handle = new TCP(); + +// Should be able to bind to the common.PORT +var err = handle.bind('0.0.0.0', common.PORT); +assert.equal(err, 0); + +// Should not be able to bind to the same port again +err = handle.bind('0.0.0.0', common.PORT); +assert.equal(err, uv.UV_EINVAL); + +handle.close(); diff --git a/test/parallel/test-timers-first-fire.js b/test/parallel/test-timers-first-fire.js new file mode 100644 index 000000000..e97b7ec85 --- /dev/null +++ b/test/parallel/test-timers-first-fire.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TIMEOUT = 50; +var last = process.hrtime(); +setTimeout(function() { + var hr = process.hrtime(last); + var ms = (hr[0] * 1e3) + (hr[1] / 1e6); + var delta = ms - TIMEOUT; + console.log('timer fired in', delta); + assert.ok(delta > 0, 'Timer fired early'); +}, TIMEOUT); diff --git a/test/parallel/test-timers-immediate-queue.js b/test/parallel/test-timers-immediate-queue.js new file mode 100644 index 000000000..cce43a1ac --- /dev/null +++ b/test/parallel/test-timers-immediate-queue.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// setImmediate should run clear its queued cbs once per event loop turn +// but immediates queued while processing the current queue should happen +// on the next turn of the event loop. + +// in v0.10 hit should be 1, because we only process one cb per turn +// in v0.11 and beyond it should be the exact same size of QUEUE +// if we're letting things recursively add to the immediate QUEUE hit will be +// > QUEUE + +var ticked = false; + +var hit = 0; +var QUEUE = 1000; + +function run() { + if (hit === 0) + process.nextTick(function() { ticked = true; }); + + if (ticked) return; + + hit += 1; + setImmediate(run); +} + +for (var i = 0; i < QUEUE; i++) + setImmediate(run); + +process.on('exit', function() { + console.log('hit', hit); + assert.strictEqual(hit, QUEUE, 'We ticked between the immediate queue'); +}); diff --git a/test/parallel/test-timers-immediate.js b/test/parallel/test-timers-immediate.js new file mode 100644 index 000000000..0bd8ae964 --- /dev/null +++ b/test/parallel/test-timers-immediate.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var immediateA = false, + immediateB = false, + immediateC = [], + before; + +setImmediate(function() { + try { + immediateA = process.hrtime(before); + } catch(e) { + console.log('failed to get hrtime with offset'); + } + clearImmediate(immediateB); +}); + +before = process.hrtime(); + +immediateB = setImmediate(function() { + immediateB = true; +}); + +setImmediate(function(x, y, z) { + immediateC = [x, y, z]; +}, 1, 2, 3); + +process.on('exit', function() { + assert.ok(immediateA, 'Immediate should happen after normal execution'); + assert.notStrictEqual(immediateB, true, 'immediateB should not fire'); + assert.deepEqual(immediateC, [1, 2, 3], 'immediateC args should match'); +}); diff --git a/test/parallel/test-timers-linked-list.js b/test/parallel/test-timers-linked-list.js new file mode 100644 index 000000000..0b6bf4bef --- /dev/null +++ b/test/parallel/test-timers-linked-list.js @@ -0,0 +1,120 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var L = require('_linklist'); + + +var list = { name: 'list' }; +var A = { name: 'A' }; +var B = { name: 'B' }; +var C = { name: 'C' }; +var D = { name: 'D' }; + + +L.init(list); +L.init(A); +L.init(B); +L.init(C); +L.init(D); + +assert.ok(L.isEmpty(list)); +assert.equal(null, L.peek(list)); + +L.append(list, A); +// list -> A +assert.equal(A, L.peek(list)); + +L.append(list, B); +// list -> A -> B +assert.equal(A, L.peek(list)); + +L.append(list, C); +// list -> A -> B -> C +assert.equal(A, L.peek(list)); + +L.append(list, D); +// list -> A -> B -> C -> D +assert.equal(A, L.peek(list)); + +var x = L.shift(list); +assert.equal(A, x); +// list -> B -> C -> D +assert.equal(B, L.peek(list)); + +x = L.shift(list); +assert.equal(B, x); +// list -> C -> D +assert.equal(C, L.peek(list)); + +// B is already removed, so removing it again shouldn't hurt. +L.remove(B); +// list -> C -> D +assert.equal(C, L.peek(list)); + +// Put B back on the list +L.append(list, B); +// list -> C -> D -> B +assert.equal(C, L.peek(list)); + +L.remove(C); +// list -> D -> B +assert.equal(D, L.peek(list)); + +L.remove(B); +// list -> D +assert.equal(D, L.peek(list)); + +L.remove(D); +// list +assert.equal(null, L.peek(list)); + + +assert.ok(L.isEmpty(list)); + + +L.append(list, D); +// list -> D +assert.equal(D, L.peek(list)); + +L.append(list, C); +L.append(list, B); +L.append(list, A); +// list -> D -> C -> B -> A + +// Append should REMOVE C from the list and append it to the end. +L.append(list, C); + +// list -> D -> B -> A -> C +assert.equal(D, L.shift(list)); +// list -> B -> A -> C +assert.equal(B, L.peek(list)); +assert.equal(B, L.shift(list)); +// list -> A -> C +assert.equal(A, L.peek(list)); +assert.equal(A, L.shift(list)); +// list -> C +assert.equal(C, L.peek(list)); +assert.equal(C, L.shift(list)); +// list +assert.ok(L.isEmpty(list)); + diff --git a/test/parallel/test-timers-non-integer-delay.js b/test/parallel/test-timers-non-integer-delay.js new file mode 100644 index 000000000..db9bedafa --- /dev/null +++ b/test/parallel/test-timers-non-integer-delay.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * This test makes sure that non-integer timer delays do not make the process + * hang. See https://github.com/joyent/node/issues/8065 and + * https://github.com/joyent/node/issues/8068 which have been fixed by + * https://github.com/joyent/node/pull/8073. + * + * If the process hangs, this test will make the tests suite timeout, + * otherwise it will exit very quickly (after 50 timers with a short delay + * fire). + * + * We have to set at least several timers with a non-integer delay to + * reproduce the issue. Sometimes, a timer with a non-integer delay will + * expire correctly. 50 timers has always been more than enough to reproduce + * it 100%. + */ + +var assert = require('assert'); + +var TIMEOUT_DELAY = 1.1; +var NB_TIMEOUTS_FIRED = 50; + +var nbTimeoutFired = 0; +var interval = setInterval(function() { + ++nbTimeoutFired; + if (nbTimeoutFired === NB_TIMEOUTS_FIRED) { + clearInterval(interval); + process.exit(0); + } +}, TIMEOUT_DELAY); diff --git a/test/parallel/test-timers-ordering.js b/test/parallel/test-timers-ordering.js new file mode 100644 index 000000000..30cc44e53 --- /dev/null +++ b/test/parallel/test-timers-ordering.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Timer = process.binding('timer_wrap').Timer; + +var i; + +var N = 30; + +var last_i = 0; +var last_ts = 0; +var start = Timer.now(); + +var f = function(i) { + if (i <= N) { + // check order + assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + last_i + ' + 1'); + last_i = i; + + // check that this iteration is fired at least 1ms later than the previous + var now = Timer.now(); + console.log(i, now); + assert(now >= last_ts + 1, 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); + last_ts = now; + + // schedule next iteration + setTimeout(f, 1, i + 1); + } +}; +f(1); diff --git a/test/parallel/test-timers-this.js b/test/parallel/test-timers-this.js new file mode 100644 index 000000000..3d23e61df --- /dev/null +++ b/test/parallel/test-timers-this.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); + +var immediateThis, intervalThis, timeoutThis, + immediateArgsThis, intervalArgsThis, timeoutArgsThis; + +var immediateHandler = setImmediate(function () { + immediateThis = this; +}); + +var immediateArgsHandler = setImmediate(function () { + immediateArgsThis = this; +}, "args ..."); + +var intervalHandler = setInterval(function () { + clearInterval(intervalHandler); + + intervalThis = this; +}); + +var intervalArgsHandler = setInterval(function () { + clearInterval(intervalArgsHandler); + + intervalArgsThis = this; +}, 0, "args ..."); + +var timeoutHandler = setTimeout(function () { + timeoutThis = this; +}); + +var timeoutArgsHandler = setTimeout(function () { + timeoutArgsThis = this; +}, 0, "args ..."); + +process.once('exit', function () { + assert.strictEqual(immediateThis, immediateHandler); + assert.strictEqual(immediateArgsThis, immediateArgsHandler); + + assert.strictEqual(intervalThis, intervalHandler); + assert.strictEqual(intervalArgsThis, intervalArgsHandler); + + assert.strictEqual(timeoutThis, timeoutHandler); + assert.strictEqual(timeoutArgsThis, timeoutArgsHandler); +}); diff --git a/test/parallel/test-timers-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js new file mode 100644 index 000000000..6e07fe084 --- /dev/null +++ b/test/parallel/test-timers-uncaught-exception.js @@ -0,0 +1,60 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var exceptions = 0; +var timer1 = 0; +var timer2 = 0; + +// the first timer throws... +console.error('set first timer'); +setTimeout(function() { + console.error('first timer'); + timer1++; + throw new Error('BAM!'); +}, 100); + +// ...but the second one should still run +console.error('set second timer'); +setTimeout(function() { + console.error('second timer'); + assert.equal(timer1, 1); + timer2++; +}, 100); + +function uncaughtException(err) { + console.error('uncaught handler'); + assert.equal(err.message, 'BAM!'); + exceptions++; +} +process.on('uncaughtException', uncaughtException); + +var exited = false; +process.on('exit', function() { + assert(!exited); + exited = true; + process.removeListener('uncaughtException', uncaughtException); + assert.equal(exceptions, 1); + assert.equal(timer1, 1); + assert.equal(timer2, 1); +}); diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js new file mode 100644 index 000000000..1c362cb83 --- /dev/null +++ b/test/parallel/test-timers-unref.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var interval_fired = false, + timeout_fired = false, + unref_interval = false, + unref_timer = false, + interval, check_unref, checks = 0; + +var LONG_TIME = 10 * 1000; +var SHORT_TIME = 100; + +setInterval(function() { + interval_fired = true; +}, LONG_TIME).unref(); + +setTimeout(function() { + timeout_fired = true; +}, LONG_TIME).unref(); + +interval = setInterval(function() { + unref_interval = true; + clearInterval(interval); +}, SHORT_TIME).unref(); + +setTimeout(function() { + unref_timer = true; +}, SHORT_TIME).unref(); + +check_unref = setInterval(function() { + if (checks > 5 || (unref_interval && unref_timer)) + clearInterval(check_unref); + checks += 1; +}, 100); + +// Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. +(function() { + var t = setInterval(function() {}, 1); + process.nextTick(t.unref.bind({})); + process.nextTick(t.unref.bind(t)); +})(); + +process.on('exit', function() { + assert.strictEqual(interval_fired, false, 'Interval should not fire'); + assert.strictEqual(timeout_fired, false, 'Timeout should not fire'); + assert.strictEqual(unref_timer, true, 'An unrefd timeout should still fire'); + assert.strictEqual(unref_interval, true, 'An unrefd interval should still fire'); +}); diff --git a/test/parallel/test-timers-zero-timeout.js b/test/parallel/test-timers-zero-timeout.js new file mode 100644 index 000000000..eb43f183f --- /dev/null +++ b/test/parallel/test-timers-zero-timeout.js @@ -0,0 +1,59 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// https://github.com/joyent/node/issues/2079 - zero timeout drops extra args +(function() { + var ncalled = 0; + + setTimeout(f, 0, 'foo', 'bar', 'baz'); + var timer = setTimeout(function() {}, 0); + + function f(a, b, c) { + assert.equal(a, 'foo'); + assert.equal(b, 'bar'); + assert.equal(c, 'baz'); + ncalled++; + } + + process.on('exit', function() { + assert.equal(ncalled, 1); + }); +})(); + +(function() { + var ncalled = 0; + + var iv = setInterval(f, 0, 'foo', 'bar', 'baz'); + + function f(a, b, c) { + assert.equal(a, 'foo'); + assert.equal(b, 'bar'); + assert.equal(c, 'baz'); + if (++ncalled == 3) clearTimeout(iv); + } + + process.on('exit', function() { + assert.equal(ncalled, 3); + }); +})(); diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js new file mode 100644 index 000000000..98e6bc3de --- /dev/null +++ b/test/parallel/test-timers.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var inputs = [ + undefined, + null, + true, + false, + '', + [], + {}, + NaN, + +Infinity, + -Infinity, + (1.0 / 0.0), // sanity check + parseFloat('x'), // NaN + -10, + -1, + -0.5, + -0.0, + 0, + 0.0, + 0.5, + 1, + 1.0, + 10, + 2147483648, // browser behaviour: timeouts > 2^31-1 run on next tick + 12345678901234 // ditto +]; + +var timeouts = []; +var intervals = []; + +inputs.forEach(function(value, index) { + setTimeout(function() { + timeouts[index] = true; + }, value); + + var handle = setInterval(function() { + clearInterval(handle); // disarm timer or we'll never finish + intervals[index] = true; + }, value); +}); + +process.on('exit', function() { + // assert that all timers have run + inputs.forEach(function(value, index) { + assert.equal(true, timeouts[index]); + assert.equal(true, intervals[index]); + }); +}); diff --git a/test/parallel/test-tls-0-dns-altname.js b/test/parallel/test-tls-0-dns-altname.js new file mode 100644 index 000000000..002a5ca3c --- /dev/null +++ b/test/parallel/test-tls-0-dns-altname.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); +var tls = require('tls'); + +var common = require('../common'); + +var requests = 0; + +var server = tls.createServer({ + key: fs.readFileSync(common.fixturesDir + '/keys/0-dns-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/0-dns-cert.pem') +}, function(c) { + c.once('data', function() { + c.destroy(); + server.close(); + }); +}).listen(common.PORT, function() { + var c = tls.connect(common.PORT, { + rejectUnauthorized: false + }, function() { + requests++; + var cert = c.getPeerCertificate(); + assert.equal(cert.subjectaltname, + 'DNS:google.com\0.evil.com, ' + + 'DNS:just-another.com, ' + + 'IP Address:8.8.8.8, '+ + 'IP Address:8.8.4.4, '+ + 'DNS:last.com'); + c.write('ok'); + }); +}); + +process.on('exit', function() { + assert.equal(requests, 1); +}); diff --git a/test/parallel/test-tls-alert.js b/test/parallel/test-tls-alert.js new file mode 100644 index 000000000..f26b496f9 --- /dev/null +++ b/test/parallel/test-tls-alert.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var spawn = require('child_process').spawn; + +var success = false; + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var server = tls.Server({ + secureProtocol: 'TLSv1_2_server_method', + key: loadPEM('agent2-key'), + cert:loadPEM('agent2-cert') +}, null).listen(common.PORT, function() { + var args = ['s_client', '-quiet', '-tls1_1','-connect', '127.0.0.1:' + common.PORT]; + var client = spawn(common.opensslCli, args); + var out = ''; + client.stderr.setEncoding('utf8'); + client.stderr.on('data', function(d) { + out += d; + if (/SSL alert number 70/.test(out)) { + success = true; + server.close(); + } + }); +}); +process.on('exit', function() { + assert(success); +}); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js new file mode 100644 index 000000000..ec8369ba9 --- /dev/null +++ b/test/parallel/test-tls-cert-regression.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var tls = require('tls'); + +var assert = require('assert'); +var common = require('../common'); + +var cert = '-----BEGIN CERTIFICATE-----\n' + + 'MIIBfjCCASgCCQDmmNjAojbDQjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\n' + + 'VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\n' + + 'cyBQdHkgTHRkMCAXDTE0MDExNjE3NTMxM1oYDzIyODcxMDMxMTc1MzEzWjBFMQsw\n' + + 'CQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJu\n' + + 'ZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPKwlfMX\n' + + '6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+wsU1O9FzRIVmpeIjDXhbp\n' + + 'Mjsa1HtzSiccPXsCAwEAATANBgkqhkiG9w0BAQUFAANBAHOoKy0NkyfiYH7Ne5ka\n' + + 'uvCyndyeB4d24FlfqEUlkfaWCZlNKRaV9YhLDiEg3BcIreFo4brtKQfZzTRs0GVm\n' + + 'KHg=\n' + + '-----END CERTIFICATE-----'; +var key = '-----BEGIN RSA PRIVATE KEY-----\n' + + 'MIIBPQIBAAJBAPKwlfMX6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+w\n' + + 'sU1O9FzRIVmpeIjDXhbpMjsa1HtzSiccPXsCAwEAAQJBAM4uU9aJE0OfdE1p/X+K\n' + + 'LrCT3XMdFCJ24GgmHyOURtwDy18upQJecDVdcZp16fjtOPmaW95GoYRyifB3R4I5\n' + + 'RxECIQD7jRM9slCSVV8xp9kOJQNpHjhRQYVGBn+pyllS2sb+RQIhAPb7Y+BIccri\n' + + 'NWnuhwCW8hA7Fkj/kaBdAwyW7L3Tvui/AiEAiqLCovMecre4Yi6GcsQ1b/6mvSmm\n' + + 'IOS+AT6zIfXPTB0CIQCJKGR3ymN/Qw5crL1GQ41cHCQtF9ickOq/lBUW+j976wIh\n' + + 'AOaJnkQrmurlRdePX6LvN/LgGAQoxwovfjcOYNnZsIVY\n' + + '-----END RSA PRIVATE KEY-----'; + +function test(cert, key, cb) { + var server = tls.createServer({ + cert: cert, + key: key + }).listen(common.PORT, function() { + server.close(cb); + }); +} + +var completed = false; +test(cert, key, function() { + test(new Buffer(cert), new Buffer(key), function() { + completed = true; + }); +}); + +process.on('exit', function() { + assert(completed); +}); diff --git a/test/parallel/test-tls-check-server-identity.js b/test/parallel/test-tls-check-server-identity.js new file mode 100644 index 000000000..598dac0e0 --- /dev/null +++ b/test/parallel/test-tls-check-server-identity.js @@ -0,0 +1,217 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var tls = require('tls'); + +var tests = [ + // Basic CN handling + { host: 'a.com', cert: { subject: { CN: 'a.com' } } }, + { host: 'a.com', cert: { subject: { CN: 'A.COM' } } }, + { + host: 'a.com', + cert: { subject: { CN: 'b.com' } }, + error: 'Host: a.com. is not cert\'s CN: b.com' + }, + { host: 'a.com', cert: { subject: { CN: 'a.com.' } } }, + + // Wildcards in CN + { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } } }, + { host: 'b.a.com', cert: { + subjectaltname: 'DNS:omg.com', + subject: { CN: '*.a.com' } }, + error: 'Host: b.a.com. is not in the cert\'s altnames: ' + + 'DNS:omg.com' + }, + + // Multiple CN fields + { + host: 'foo.com', cert: { + subject: { CN: ['foo.com', 'bar.com'] } // CN=foo.com; CN=bar.com; + } + }, + + // DNS names and CN + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*', + subject: { CN: 'b.com' } + }, + error: 'Host: a.com. is not in the cert\'s altnames: ' + + 'DNS:*' + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.com', + subject: { CN: 'b.com' } + }, + error: 'Host: a.com. is not in the cert\'s altnames: ' + + 'DNS:*.com' + }, + { + host: 'a.co.uk', cert: { + subjectaltname: 'DNS:*.co.uk', + subject: { CN: 'b.com' } + } + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: { CN: 'a.com' } + }, + error: 'Host: a.com. is not in the cert\'s altnames: ' + + 'DNS:*.a.com' + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: { CN: 'b.com' } + }, + error: 'Host: a.com. is not in the cert\'s altnames: ' + + 'DNS:*.a.com' + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:a.com', + subject: { CN: 'b.com' } + } + }, + { + host: 'a.com', cert: { + subjectaltname: 'DNS:A.COM', + subject: { CN: 'b.com' } + } + }, + + // DNS names + { + host: 'a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: {} + }, + error: 'Host: a.com. is not in the cert\'s altnames: ' + + 'DNS:*.a.com' + }, + { + host: 'b.a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: {} + } + }, + { + host: 'c.b.a.com', cert: { + subjectaltname: 'DNS:*.a.com', + subject: {} + }, + error: 'Host: c.b.a.com. is not in the cert\'s altnames: ' + + 'DNS:*.a.com' + }, + { + host: 'b.a.com', cert: { + subjectaltname: 'DNS:*b.a.com', + subject: {} + } + }, + { + host: 'a-cb.a.com', cert: { + subjectaltname: 'DNS:*b.a.com', + subject: {} + } + }, + { + host: 'a.b.a.com', cert: { + subjectaltname: 'DNS:*b.a.com', + subject: {} + }, + error: 'Host: a.b.a.com. is not in the cert\'s altnames: ' + + 'DNS:*b.a.com' + }, + // Mutliple DNS names + { + host: 'a.b.a.com', cert: { + subjectaltname: 'DNS:*b.a.com, DNS:a.b.a.com', + subject: {} + } + }, + // URI names + { + host: 'a.b.a.com', cert: { + subjectaltname: 'URI:http://a.b.a.com/', + subject: {} + } + }, + { + host: 'a.b.a.com', cert: { + subjectaltname: 'URI:http://*.b.a.com/', + subject: {} + }, + error: 'Host: a.b.a.com. is not in the cert\'s altnames: ' + + 'URI:http://*.b.a.com/' + }, + // IP addresses + { + host: 'a.b.a.com', cert: { + subjectaltname: 'IP Address:127.0.0.1', + subject: {} + }, + error: 'Host: a.b.a.com. is not in the cert\'s altnames: ' + + 'IP Address:127.0.0.1' + }, + { + host: '127.0.0.1', cert: { + subjectaltname: 'IP Address:127.0.0.1', + subject: {} + } + }, + { + host: '127.0.0.2', cert: { + subjectaltname: 'IP Address:127.0.0.1', + subject: {} + }, + error: 'IP: 127.0.0.2 is not in the cert\'s list: ' + + '127.0.0.1' + }, + { + host: '127.0.0.1', cert: { + subjectaltname: 'DNS:a.com', + subject: {} + }, + error: 'IP: 127.0.0.1 is not in the cert\'s list: ' + }, + { + host: 'localhost', cert: { + subjectaltname: 'DNS:a.com', + subject: { CN: 'localhost' } + }, + error: 'Host: localhost. is not in the cert\'s altnames: ' + + 'DNS:a.com' + }, +]; + +tests.forEach(function(test, i) { + var err = tls.checkServerIdentity(test.host, test.cert); + assert.equal(err && err.reason, + test.error, + 'Test#' + i + ' failed: ' + util.inspect(test) + '\n' + + test.error + ' != ' + (err && err.reason)); +}); diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js new file mode 100644 index 000000000..8958ceb15 --- /dev/null +++ b/test/parallel/test-tls-client-abort.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var path = require('path'); + +var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); +var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); + +var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { + assert.ok(false); // callback should never be executed +}); +conn.on('error', function() { +}); +assert.doesNotThrow(function() { + conn.destroy(); +}); + diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js new file mode 100644 index 000000000..f81196276 --- /dev/null +++ b/test/parallel/test-tls-client-abort2.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); + +var errors = 0; + +var conn = tls.connect(common.PORT, function() { + assert(false); // callback should never be executed +}); +conn.on('error', function() { + ++errors; + assert.doesNotThrow(function() { + conn.destroy(); + }); +}); + +process.on('exit', function() { + assert.equal(errors, 1); +}); diff --git a/test/parallel/test-tls-client-default-ciphers.js b/test/parallel/test-tls-client-default-ciphers.js new file mode 100644 index 000000000..0a3c47029 --- /dev/null +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var tls = require('tls'); + +function test1() { + var ciphers = ''; + tls.createSecureContext = function(options) { + ciphers = options.ciphers + } + var s = tls.connect(common.PORT); + s.destroy(); + assert.equal(ciphers, tls.DEFAULT_CIPHERS); +} +test1(); diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js new file mode 100644 index 000000000..529b84a73 --- /dev/null +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Create an ssl server. First connection, validate that not resume. +// Cache session and close connection. Use session on second connection. +// ASSERT resumption. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var big = new Buffer(2 * 1024 * 1024); +var connections = 0; +var bytesRead = 0; + +big.fill('Y'); + +// create server +var server = tls.createServer(options, function(socket) { + socket.end(big); + socket.destroySoon(); + connections++; +}); + +// start listening +server.listen(common.PORT, function() { + var client = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + client.on('readable', function() { + var d = client.read(); + if (d) + bytesRead += d.length; + }); + + client.on('end', function() { + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(1, connections); + assert.equal(big.length, bytesRead); +}); diff --git a/test/parallel/test-tls-client-reject.js b/test/parallel/test-tls-client-reject.js new file mode 100644 index 000000000..bae961498 --- /dev/null +++ b/test/parallel/test-tls-client-reject.js @@ -0,0 +1,96 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var connectCount = 0; + +var server = tls.createServer(options, function(socket) { + ++connectCount; + socket.on('data', function(data) { + common.debug(data.toString()); + assert.equal(data, 'ok'); + }); +}).listen(common.PORT, function() { + unauthorized(); +}); + +function unauthorized() { + var socket = tls.connect({ + port: common.PORT, + servername: 'localhost', + rejectUnauthorized: false + }, function() { + assert(!socket.authorized); + socket.end(); + rejectUnauthorized(); + }); + socket.on('error', function(err) { + assert(false); + }); + socket.write('ok'); +} + +function rejectUnauthorized() { + var socket = tls.connect(common.PORT, { + servername: 'localhost' + }, function() { + assert(false); + }); + socket.on('error', function(err) { + common.debug(err); + authorized(); + }); + socket.write('ng'); +} + +function authorized() { + var socket = tls.connect(common.PORT, { + ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))], + servername: 'localhost' + }, function() { + assert(socket.authorized); + socket.end(); + server.close(); + }); + socket.on('error', function(err) { + assert(false); + }); + socket.write('ok'); +} + +process.on('exit', function() { + assert.equal(connectCount, 3); +}); diff --git a/test/parallel/test-tls-client-resume.js b/test/parallel/test-tls-client-resume.js new file mode 100644 index 000000000..7271134df --- /dev/null +++ b/test/parallel/test-tls-client-resume.js @@ -0,0 +1,85 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Create an ssl server. First connection, validate that not resume. +// Cache session and close connection. Use session on second connection. +// ASSERT resumption. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; + +// create server +var server = tls.Server(options, function(socket) { + socket.end('Goodbye'); + connections++; +}); + +// start listening +server.listen(common.PORT, function() { + + var session1 = null; + var client1 = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + console.log('connect1'); + assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); + session1 = client1.getSession(); + }); + + client1.on('close', function() { + console.log('close1'); + + var opts = { + port: common.PORT, + rejectUnauthorized: false, + session: session1 + }; + + var client2 = tls.connect(opts, function() { + console.log('connect2'); + assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); + }); + + client2.on('close', function() { + console.log('close2'); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(2, connections); +}); diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js new file mode 100644 index 000000000..590dfc6e6 --- /dev/null +++ b/test/parallel/test-tls-client-verify.js @@ -0,0 +1,155 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + + +var hosterr = /Hostname\/IP doesn\'t match certificate\'s altnames/g; +var testCases = + [{ ca: ['ca1-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: 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: ['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' } + ] + } + ]; + + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); + + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var successfulTests = 0; + +function testServers(index, servers, clientOptions, cb) { + var serverOptions = servers[index]; + if (!serverOptions) { + cb(); + return; + } + + var ok = serverOptions.ok; + + if (serverOptions.key) { + serverOptions.key = loadPEM(serverOptions.key); + } + + if (serverOptions.cert) { + serverOptions.cert = loadPEM(serverOptions.cert); + } + + var server = tls.createServer(serverOptions, function(s) { + s.end('hello world\n'); + }); + + server.listen(common.PORT, function() { + var b = ''; + + console.error('connecting...'); + var client = tls.connect(clientOptions, function() { + var authorized = client.authorized || + hosterr.test(client.authorizationError); + + console.error('expected: ' + ok + ' authed: ' + authorized); + + assert.equal(ok, authorized); + server.close(); + }); + + client.on('data', function(d) { + b += d.toString(); + }); + + client.on('end', function() { + assert.equal('hello world\n', b); + }); + + client.on('close', function() { + testServers(index + 1, servers, clientOptions, cb); + }); + }); +} + + +function runTest(testIndex) { + var tcase = testCases[testIndex]; + if (!tcase) return; + + var clientOptions = { + port: common.PORT, + ca: tcase.ca.map(loadPEM), + key: loadPEM(tcase.key), + cert: loadPEM(tcase.cert), + rejectUnauthorized: false + }; + + + testServers(0, tcase.servers, clientOptions, function() { + successfulTests++; + runTest(testIndex + 1); + }); +} + + +runTest(0); + + +process.on('exit', function() { + console.log('successful tests: %d', successfulTests); + assert.equal(successfulTests, testCases.length); +}); diff --git a/test/parallel/test-tls-close-notify.js b/test/parallel/test-tls-close-notify.js new file mode 100644 index 000000000..3c6bf53f2 --- /dev/null +++ b/test/parallel/test-tls-close-notify.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); +var tls = require('tls'); + +var common = require('../common'); + +var ended = 0; + +var server = tls.createServer({ + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}, function(c) { + // Send close-notify without shutting down TCP socket + if (c.ssl.shutdown() !== 1) + c.ssl.shutdown(); +}).listen(common.PORT, function() { + var c = tls.connect(common.PORT, { + rejectUnauthorized: false + }, function() { + // Ensure that we receive 'end' event anyway + c.on('end', function() { + ended++; + c.destroy(); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(ended, 1); +}); diff --git a/test/parallel/test-tls-connect-given-socket.js b/test/parallel/test-tls-connect-given-socket.js new file mode 100644 index 000000000..ab571c7a8 --- /dev/null +++ b/test/parallel/test-tls-connect-given-socket.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var net = require('net'); +var fs = require('fs'); +var path = require('path'); + +var serverConnected = 0; +var clientConnected = 0; + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var server = tls.createServer(options, function(socket) { + serverConnected++; + socket.end('Hello'); +}).listen(common.PORT, function() { + var waiting = 2; + function establish(socket) { + var client = tls.connect({ + rejectUnauthorized: false, + socket: socket + }, function() { + clientConnected++; + var data = ''; + client.on('data', function(chunk) { + data += chunk.toString(); + }); + client.on('end', function() { + assert.equal(data, 'Hello'); + if (--waiting === 0) + server.close(); + }); + }); + assert(client.readable); + assert(client.writable); + } + + // Already connected socket + var connected = net.connect(common.PORT, function() { + establish(connected); + }); + + // Connecting socket + var connecting = net.connect(common.PORT); + establish(connecting); +}); + +process.on('exit', function() { + assert.equal(serverConnected, 2); + assert.equal(clientConnected, 2); +}); diff --git a/test/parallel/test-tls-connect-pipe.js b/test/parallel/test-tls-connect-pipe.js new file mode 100644 index 000000000..98031c0ad --- /dev/null +++ b/test/parallel/test-tls-connect-pipe.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var clientConnected = 0; +var serverConnected = 0; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.Server(options, function(socket) { + ++serverConnected; + server.close(); +}); +server.listen(common.PIPE, function() { + var options = { rejectUnauthorized: false }; + var client = tls.connect(common.PIPE, options, function() { + ++clientConnected; + client.end(); + }); +}); + +process.on('exit', function() { + assert.equal(clientConnected, 1); + assert.equal(serverConnected, 1); +}); diff --git a/test/parallel/test-tls-connect-simple.js b/test/parallel/test-tls-connect-simple.js new file mode 100644 index 000000000..e896dd9e2 --- /dev/null +++ b/test/parallel/test-tls-connect-simple.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var clientConnected = 0; +var serverConnected = 0; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.Server(options, function(socket) { + if (++serverConnected === 2) { + server.close(); + } +}); + +server.listen(common.PORT, function() { + var client1 = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + ++clientConnected; + client1.end(); + }); + + var client2 = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }); + client2.on('secureConnect', function() { + ++clientConnected; + client2.end(); + }); +}); + +process.on('exit', function() { + assert.equal(clientConnected, 2); + assert.equal(serverConnected, 2); +}); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js new file mode 100644 index 000000000..616f76c05 --- /dev/null +++ b/test/parallel/test-tls-connect.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var path = require('path'); + +// https://github.com/joyent/node/issues/1218 +// uncatchable exception on TLS connection error +(function() { + var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); + + var errorEmitted = false; + + process.on('exit', function() { + assert.ok(errorEmitted); + }); + + var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { + assert.ok(false); // callback should never be executed + }); + + conn.on('error', function() { + errorEmitted = true; + }); +})(); + +// SSL_accept/SSL_connect error handling +(function() { + var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); + + var errorEmitted = false; + + process.on('exit', function() { + assert.ok(errorEmitted); + }); + + var conn = tls.connect({ + cert: cert, + key: key, + port: common.PORT, + ciphers: 'rick-128-roll' + }, function() { + assert.ok(false); // callback should never be executed + }); + + conn.on('error', function() { + errorEmitted = true; + }); +})(); diff --git a/test/parallel/test-tls-delayed-attach.js b/test/parallel/test-tls-delayed-attach.js new file mode 100644 index 000000000..ceacedc73 --- /dev/null +++ b/test/parallel/test-tls-delayed-attach.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); +var tls = require('tls'); + +var common = require('../common'); + +var sent = 'hello world'; +var received = ''; +var ended = 0; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = net.createServer(function(c) { + setTimeout(function() { + var s = new tls.TLSSocket(c, { + isServer: true, + secureContext: tls.createSecureContext(options) + }); + + s.on('data', function(chunk) { + received += chunk; + }); + + s.on('end', function() { + ended++; + server.close(); + s.destroy(); + }); + }, 200); +}).listen(common.PORT, function() { + var c = tls.connect(common.PORT, { + rejectUnauthorized: false + }, function() { + c.end(sent); + }); +}); + +process.on('exit', function() { + assert.equal(received, sent); + assert.equal(ended, 1); +}); diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js new file mode 100644 index 000000000..3975c5ed4 --- /dev/null +++ b/test/parallel/test-tls-dhe.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var spawn = require('child_process').spawn; +var tls = require('tls'); +var fs = require('fs'); +var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); +var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); +var nsuccess = 0; +var ntests = 0; +var ciphers = 'DHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256'; + + +function loadDHParam(n) { + var path = common.fixturesDir; + if (n !== 'error') path += '/keys'; + return fs.readFileSync(path + '/dh' + n + '.pem'); +} + +function test(keylen, expectedCipher, cb) { + var options = { + key: key, + cert: cert, + dhparam: loadDHParam(keylen) + }; + + var server = tls.createServer(options, function(conn) { + conn.end(); + }); + + server.on('close', function(err) { + assert(!err); + if (cb) cb(); + }); + + server.listen(common.PORT, '127.0.0.1', function() { + var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT, + '-cipher', ciphers]; + var client = spawn(common.opensslCli, args); + var out = ''; + client.stdout.setEncoding('utf8'); + client.stdout.on('data', function(d) { + out += d; + }); + client.stdout.on('end', function() { + // DHE key length can be checked -brief option in s_client but it + // is only supported in openssl 1.0.2 so we cannot check it. + var reg = new RegExp('Cipher : ' + expectedCipher); + if (reg.test(out)) { + nsuccess++; + server.close(); + } + }); + }); +} + +function test512() { + test(512, 'DHE-RSA-AES128-SHA256', test1024); + ntests++; +} + +function test1024() { + test(1024, 'DHE-RSA-AES128-SHA256', test2048); + ntests++; +} + +function test2048() { + test(2048, 'DHE-RSA-AES128-SHA256', testError); + ntests++; +} + +function testError() { + test('error', 'ECDHE-RSA-AES128-SHA256', null); + ntests++; +} + +test512(); + +process.on('exit', function() { + assert.equal(ntests, nsuccess); +}); diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js new file mode 100644 index 000000000..06b4e4ffd --- /dev/null +++ b/test/parallel/test-tls-ecdh-disable.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var exec = require('child_process').exec; +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: 'ECDHE-RSA-RC4-SHA', + ecdhCurve: false +}; + +var nconns = 0; + +process.on('exit', function() { + assert.equal(nconns, 0); +}); + +var server = tls.createServer(options, function(conn) { + conn.end(); + nconns++; +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var cmd = common.opensslCli + ' s_client -cipher ' + options.ciphers + + ' -connect 127.0.0.1:' + common.PORT; + + exec(cmd, function(err, stdout, stderr) { + // Old versions of openssl will still exit with 0 so we + // can't just check if err is not null. + assert.notEqual(stderr.indexOf('handshake failure'), -1); + server.close(); + }); +}); diff --git a/test/parallel/test-tls-ecdh.js b/test/parallel/test-tls-ecdh.js new file mode 100644 index 000000000..446d76c83 --- /dev/null +++ b/test/parallel/test-tls-ecdh.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var exec = require('child_process').exec; +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: '-ALL:ECDHE-RSA-RC4-SHA', + ecdhCurve: 'prime256v1' +}; + +var reply = 'I AM THE WALRUS'; // something recognizable +var nconns = 0; +var response = ''; + +process.on('exit', function() { + assert.equal(nconns, 1); + assert.notEqual(response.indexOf(reply), -1); +}); + +var server = tls.createServer(options, function(conn) { + conn.end(reply); + nconns++; +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var cmd = common.opensslCli + ' s_client -cipher ' + options.ciphers + + ' -connect 127.0.0.1:' + common.PORT; + + exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + response = stdout; + server.close(); + }); +}); diff --git a/test/parallel/test-tls-econnreset.js b/test/parallel/test-tls-econnreset.js new file mode 100644 index 000000000..fcadf13f0 --- /dev/null +++ b/test/parallel/test-tls-econnreset.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); + +var cacert = '-----BEGIN CERTIFICATE-----\n' + + 'MIIBxTCCAX8CAnXnMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n' + + 'VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\n' + + 'TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\n' + + 'bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMH0xCzAJ\n' + + 'BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZ\n' + + 'MBcGA1UEChMQU3Ryb25nTG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow\n' + + 'GAYDVQQDExFjYS5zdHJvbmdsb29wLmNvbTBMMA0GCSqGSIb3DQEBAQUAAzsAMDgC\n' + + 'MQDKbQ6rIR5t1q1v4Ha36jrq0IkyUohy9EYNvLnXUly1PGqxby0ILlAVJ8JawpY9\n' + + 'AVkCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\n' + + '+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\n' + + '-----END CERTIFICATE-----\n'; + +var cert = '-----BEGIN CERTIFICATE-----\n' + + 'MIIBfDCCATYCAgQaMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n' + + 'VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\n' + + 'TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\n' + + 'bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMBkxFzAV\n' + + 'BgNVBAMTDnN0cm9uZ2xvb3AuY29tMEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\n' + + 'I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01WpfGUaJr1a41K8Uq7xwID\n' + + 'AQABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA\n' + + 'cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU\n' + + '-----END CERTIFICATE-----\n'; + +var key = '-----BEGIN RSA PRIVATE KEY-----\n' + + 'MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo\n' + + 'mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg\n' + + '/JWMU/6hS36TsYyZMxwswQIZAPTAfht/zDLb7Hwgu2twsS1Ra9w/yyvtlwIZANET\n' + + '26votwJAHK1yUrZGA5nnp5qcmQ/JUQIZAII5YV/UUZvF9D/fUplJ7puENPWNY9bN\n' + + 'pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\n' + + 'YqrWTeQFNQ==\n' + + '-----END RSA PRIVATE KEY-----\n'; + +var ca = [ cert, cacert ]; + +var clientError = null; +var connectError = null; + +var server = tls.createServer({ ca: ca, cert: cert, key: key }, function(conn) { + throw 'unreachable'; +}).on('clientError', function(err, conn) { + assert(!clientError && conn); + clientError = err; +}).listen(common.PORT, function() { + var options = { + ciphers: 'AES128-GCM-SHA256', + port: common.PORT, + ca: ca + }; + tls.connect(options).on('error', function(err) { + assert(!connectError); + + connectError = err; + this.destroy(); + server.close(); + }).write('123'); +}); + +process.on('exit', function() { + assert(clientError); + assert(connectError); + assert(/socket hang up/.test(clientError.message)); + assert(/ECONNRESET/.test(clientError.code)); +}); diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js new file mode 100644 index 000000000..894ec346a --- /dev/null +++ b/test/parallel/test-tls-fast-writing.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var tls = require('tls'); +var fs = require('fs'); + +var PORT = common.PORT; +var dir = common.fixturesDir; +var options = { key: fs.readFileSync(dir + '/test_key.pem'), + cert: fs.readFileSync(dir + '/test_cert.pem'), + ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; + +var server = tls.createServer(options, onconnection); +var gotChunk = false; +var gotDrain = false; + +var timer = setTimeout(function() { + console.log('not ok - timed out'); + process.exit(1); +}, 500); + +function onconnection(conn) { + conn.on('data', function(c) { + if (!gotChunk) { + gotChunk = true; + console.log('ok - got chunk'); + } + + // just some basic sanity checks. + assert(c.length); + assert(Buffer.isBuffer(c)); + + if (gotDrain) + process.exit(0); + }); +} + +server.listen(PORT, function() { + var chunk = new Buffer(1024); + chunk.fill('x'); + var opt = { port: PORT, rejectUnauthorized: false }; + var conn = tls.connect(opt, function() { + conn.on('drain', ondrain); + write(); + }); + function ondrain() { + if (!gotDrain) { + gotDrain = true; + console.log('ok - got drain'); + } + if (gotChunk) + process.exit(0); + write(); + } + function write() { + // this needs to return false eventually + while (false !== conn.write(chunk)); + } +}); diff --git a/test/parallel/test-tls-friendly-error-message.js b/test/parallel/test-tls-friendly-error-message.js new file mode 100644 index 000000000..b58990765 --- /dev/null +++ b/test/parallel/test-tls-friendly-error-message.js @@ -0,0 +1,45 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); + +var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); +var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); + +tls.createServer({ key: key, cert: cert }, function(conn) { + conn.end(); + this.close(); +}).listen(common.PORT, function() { + var options = { port: this.address().port, rejectUnauthorized: true }; + tls.connect(options).on('error', common.mustCall(function(err) { + assert.equal(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); + assert.equal(err.message, 'unable to verify the first certificate'); + this.destroy(); + })); +}); diff --git a/test/parallel/test-tls-getcipher.js b/test/parallel/test-tls-getcipher.js new file mode 100644 index 000000000..22a280e58 --- /dev/null +++ b/test/parallel/test-tls-getcipher.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var cipher_list = ['RC4-SHA', 'AES256-SHA']; +var cipher_version_pattern = /TLS|SSL/; +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: cipher_list.join(':'), + honorCipherOrder: true +}; + +var nconns = 0; + +process.on('exit', function() { + assert.equal(nconns, 1); +}); + +var server = tls.createServer(options, function(cleartextStream) { + nconns++; +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var client = tls.connect({ + host: '127.0.0.1', + port: common.PORT, + rejectUnauthorized: false + }, function() { + var cipher = client.getCipher(); + assert.equal(cipher.name, cipher_list[0]); + assert(cipher_version_pattern.test(cipher.version)); + client.end(); + server.close(); + }); +}); diff --git a/test/parallel/test-tls-handshake-nohang.js b/test/parallel/test-tls-handshake-nohang.js new file mode 100644 index 000000000..de36ebb50 --- /dev/null +++ b/test/parallel/test-tls-handshake-nohang.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); + +// neither should hang +tls.createSecurePair(null, false, false, false); +tls.createSecurePair(null, true, false, false); diff --git a/test/parallel/test-tls-hello-parser-failure.js b/test/parallel/test-tls-hello-parser-failure.js new file mode 100644 index 000000000..b6c0ac228 --- /dev/null +++ b/test/parallel/test-tls-hello-parser-failure.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var tls = require('tls'); +var net = require('net'); +var fs = require('fs'); +var assert = require('assert'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/test_key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem') +}; + +var bonkers = new Buffer(1024 * 1024); +bonkers.fill(42); + +var server = tls.createServer(options, function(c) { + +}).listen(common.PORT, function() { + var client = net.connect(common.PORT, function() { + client.write(bonkers); + }); + + var once = false; + + var writeAgain = setTimeout(function() { + client.write(bonkers); + }); + + client.on('error', function(err) { + if (!once) { + clearTimeout(writeAgain); + once = true; + client.destroy(); + server.close(); + } + }); + + client.on('close', function (hadError) { + assert.strictEqual(hadError, true, 'Client never errored'); + }); +}); diff --git a/test/parallel/test-tls-inception.js b/test/parallel/test-tls-inception.js new file mode 100644 index 000000000..d15d1ebd4 --- /dev/null +++ b/test/parallel/test-tls-inception.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var fs = require('fs'); +var path = require('path'); +var net = require('net'); +var tls = require('tls'); +var assert = require('assert'); + +var options, a, b, portA, portB; +var gotHello = false; + +options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +// the "proxy" server +a = tls.createServer(options, function (socket) { + var options = { + host: '127.0.0.1', + port: b.address().port, + rejectUnauthorized: false + }; + var dest = net.connect(options); + dest.pipe(socket); + socket.pipe(dest); +}); + +// the "target" server +b = tls.createServer(options, function (socket) { + socket.end('hello'); +}); + +process.on('exit', function () { + assert(gotHello); +}); + +a.listen(common.PORT, function () { + b.listen(common.PORT + 1, function () { + options = { + host: '127.0.0.1', + port: a.address().port, + rejectUnauthorized: false + }; + var socket = tls.connect(options); + var ssl; + ssl = tls.connect({ + socket: socket, + rejectUnauthorized: false + }); + ssl.setEncoding('utf8'); + ssl.once('data', function (data) { + assert.equal('hello', data); + gotHello = true; + }); + ssl.on('end', function () { + ssl.end(); + a.close(); + b.close(); + }); + }); +}); diff --git a/test/parallel/test-tls-interleave.js b/test/parallel/test-tls-interleave.js new file mode 100644 index 000000000..8bebb807e --- /dev/null +++ b/test/parallel/test-tls-interleave.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var tls = require('tls'); +var fs = require('fs'); + +var PORT = common.PORT; +var dir = common.fixturesDir; +var options = { key: fs.readFileSync(dir + '/test_key.pem'), + cert: fs.readFileSync(dir + '/test_cert.pem'), + ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; + +var writes = [ + 'some server data', + 'and a separate packet', + 'and one more', +]; +var receivedWrites = 0; + +var server = tls.createServer(options, function(c) { + writes.forEach(function(str) { + c.write(str); + }); +}).listen(PORT, function() { + var c = tls.connect(PORT, { rejectUnauthorized: false }, function() { + c.write('some client data'); + c.on('readable', function() { + var data = c.read(); + if (data === null) + return; + + data = data.toString(); + while (data.length !== 0) { + assert.strictEqual(data.indexOf(writes[receivedWrites]), 0); + data = data.slice(writes[receivedWrites].length); + + if (++receivedWrites === writes.length) { + c.end(); + server.close(); + } + } + }); + }); +}); + +process.on('exit', function() { + assert.equal(receivedWrites, writes.length); +}); diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js new file mode 100644 index 000000000..3e877b406 --- /dev/null +++ b/test/parallel/test-tls-invoke-queued.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); +var tls = require('tls'); + +var common = require('../common'); + +var received = ''; +var ended = 0; + +var server = tls.createServer({ + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}, function(c) { + c._write('hello ', null, function() { + c._write('world!', null, function() { + c.destroy(); + }); + c._write(' gosh', null, function() {}); + }); + + server.close(); +}).listen(common.PORT, function() { + var c = tls.connect(common.PORT, { + rejectUnauthorized: false + }, function() { + c.on('data', function(chunk) { + received += chunk; + }); + c.on('end', function() { + ended++; + }); + }); +}); + +process.on('exit', function() { + assert.equal(ended, 1); + assert.equal(received, 'hello world! gosh'); +}); diff --git a/test/parallel/test-tls-junk-closes-server.js b/test/parallel/test-tls-junk-closes-server.js new file mode 100644 index 000000000..57db7f5a3 --- /dev/null +++ b/test/parallel/test-tls-junk-closes-server.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var tls = require('tls'); +var fs = require('fs'); +var net = require('net'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var server = tls.createServer(options, function(s) { + s.write('welcome!\n'); + s.pipe(s); +}); + +server.listen(common.PORT, function() { + var c = net.createConnection(common.PORT); + + c.on('connect', function() { + c.write('blah\nblah\nblah\n'); + }); + + c.on('end', function() { + server.close(); + }); + +}); + diff --git a/test/parallel/test-tls-key-mismatch.js b/test/parallel/test-tls-key-mismatch.js new file mode 100644 index 000000000..f99e9471f --- /dev/null +++ b/test/parallel/test-tls-key-mismatch.js @@ -0,0 +1,42 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var cert = null; + +assert.throws(function() { + tls.createSecureContext(options); +}); diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js new file mode 100644 index 000000000..f6fdf2512 --- /dev/null +++ b/test/parallel/test-tls-max-send-fragment.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); +var tls = require('tls'); + +var common = require('../common'); + +var buf = new Buffer(10000); +var received = 0; +var ended = 0; +var maxChunk = 768; + +var server = tls.createServer({ + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}, function(c) { + // Lower and upper limits + assert(!c.setMaxSendFragment(511)); + assert(!c.setMaxSendFragment(16385)); + + // Correct fragment size + assert(c.setMaxSendFragment(maxChunk)); + + c.end(buf); +}).listen(common.PORT, function() { + var c = tls.connect(common.PORT, { + rejectUnauthorized: false + }, function() { + c.on('data', function(chunk) { + assert(chunk.length <= maxChunk); + received += chunk.length; + }); + + // Ensure that we receive 'end' event anyway + c.on('end', function() { + ended++; + c.destroy(); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.equal(ended, 1); + assert.equal(received, buf.length); +}); diff --git a/test/parallel/test-tls-multi-key.js b/test/parallel/test-tls-multi-key.js new file mode 100644 index 000000000..e00c40409 --- /dev/null +++ b/test/parallel/test-tls-multi-key.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: [ + fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem') + ], + cert: [ + fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), + fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') + ] +}; + +var ciphers = []; + +var server = tls.createServer(options, function(conn) { + conn.end('ok'); +}).listen(common.PORT, function() { + var ecdsa = tls.connect(common.PORT, { + ciphers: 'ECDHE-ECDSA-AES256-GCM-SHA384', + rejectUnauthorized: false + }, function() { + var rsa = tls.connect(common.PORT, { + ciphers: 'ECDHE-RSA-AES256-GCM-SHA384', + rejectUnauthorized: false + }, function() { + ecdsa.destroy(); + rsa.destroy(); + + ciphers.push(ecdsa.getCipher()); + ciphers.push(rsa.getCipher()); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.deepEqual(ciphers, [{ + name: 'ECDHE-ECDSA-AES256-GCM-SHA384', + version: 'TLSv1/SSLv3' + }, { + name: 'ECDHE-RSA-AES256-GCM-SHA384', + version: 'TLSv1/SSLv3' + }]); +}); diff --git a/test/parallel/test-tls-no-cert-required.js b/test/parallel/test-tls-no-cert-required.js new file mode 100644 index 000000000..35121477f --- /dev/null +++ b/test/parallel/test-tls-no-cert-required.js @@ -0,0 +1,35 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var tls = require('tls'); + +// Omitting the cert or pfx option to tls.createServer() should not throw. +// AECDH-NULL-SHA is a no-authentication/no-encryption cipher and hence +// doesn't need a certificate. +tls.createServer({ ciphers: 'AECDH-NULL-SHA' }).listen(common.PORT, function() { + this.close(); +}); diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js new file mode 100644 index 000000000..d50eab942 --- /dev/null +++ b/test/parallel/test-tls-no-rsa-key.js @@ -0,0 +1,55 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') +}; + +var cert = null; + +var server = tls.createServer(options, function(conn) { + conn.end('ok'); +}).listen(common.PORT, function() { + var c = tls.connect(common.PORT, { + rejectUnauthorized: false + }, function() { + cert = c.getPeerCertificate(); + c.destroy(); + server.close(); + }); +}); + +process.on('exit', function() { + assert(cert); + assert.equal(cert.subject.C, 'US'); +}); diff --git a/test/parallel/test-tls-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js new file mode 100644 index 000000000..0849cc8d2 --- /dev/null +++ b/test/parallel/test-tls-npn-server-client.js @@ -0,0 +1,122 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.features.tls_npn) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} + +var common = require('../common'), + assert = require('assert'), + fs = require('fs'), + tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var serverOptions = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + crl: loadPEM('ca2-crl'), + SNICallback: function(servername, cb) { + cb(null, tls.createSecureContext({ + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + crl: loadPEM('ca2-crl'), + })); + }, + NPNProtocols: ['a', 'b', 'c'] +}; + +var serverPort = common.PORT; + +var clientsOptions = [{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['a', 'b', 'c'], + rejectUnauthorized: false +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['c', 'b', 'e'], + rejectUnauthorized: false +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + rejectUnauthorized: false +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['first-priority-unsupported', 'x', 'y'], + rejectUnauthorized: false +}]; + +var serverResults = [], + clientsResults = []; + +var server = tls.createServer(serverOptions, function(c) { + serverResults.push(c.npnProtocol); +}); +server.listen(serverPort, startTest); + +function startTest() { + function connectClient(options, callback) { + var client = tls.connect(options, function() { + clientsResults.push(client.npnProtocol); + client.destroy(); + + callback(); + }); + }; + + connectClient(clientsOptions[0], function() { + connectClient(clientsOptions[1], function() { + connectClient(clientsOptions[2], function() { + connectClient(clientsOptions[3], function() { + server.close(); + }); + }); + }); + }); +} + +process.on('exit', function() { + assert.equal(serverResults[0], clientsResults[0]); + assert.equal(serverResults[1], clientsResults[1]); + assert.equal(serverResults[2], 'http/1.1'); + assert.equal(clientsResults[2], false); + assert.equal(serverResults[3], 'first-priority-unsupported'); + assert.equal(clientsResults[3], false); +}); diff --git a/test/parallel/test-tls-ocsp-callback.js b/test/parallel/test-tls-ocsp-callback.js new file mode 100644 index 000000000..4c7dd1d44 --- /dev/null +++ b/test/parallel/test-tls-ocsp-callback.js @@ -0,0 +1,123 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!process.features.tls_ocsp) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var tls = require('tls'); +var constants = require('constants'); +var fs = require('fs'); +var join = require('path').join; + +test({ response: false }, function() { + test({ response: 'hello world' }, function() { + test({ ocsp: false }); + }); +}); + +function test(testOptions, cb) { + + var keyFile = join(common.fixturesDir, 'keys', 'agent1-key.pem'); + var certFile = join(common.fixturesDir, 'keys', 'agent1-cert.pem'); + var caFile = join(common.fixturesDir, 'keys', 'ca1-cert.pem'); + var key = fs.readFileSync(keyFile); + var cert = fs.readFileSync(certFile); + var ca = fs.readFileSync(caFile); + var options = { + key: key, + cert: cert, + ca: [ca] + }; + var requestCount = 0; + var clientSecure = 0; + var ocspCount = 0; + var ocspResponse; + var session; + + var server = tls.createServer(options, function(cleartext) { + cleartext.on('error', function(er) { + // We're ok with getting ECONNRESET in this test, but it's + // timing-dependent, and thus unreliable. Any other errors + // are just failures, though. + if (er.code !== 'ECONNRESET') + throw er; + }); + ++requestCount; + cleartext.end(); + }); + server.on('OCSPRequest', function(cert, issuer, callback) { + ++ocspCount; + assert.ok(Buffer.isBuffer(cert)); + assert.ok(Buffer.isBuffer(issuer)); + + // Just to check that async really works there + setTimeout(function() { + callback(null, + testOptions.response ? new Buffer(testOptions.response) : null); + }, 100); + }); + server.listen(common.PORT, function() { + var client = tls.connect({ + port: common.PORT, + requestOCSP: testOptions.ocsp !== false, + secureOptions: testOptions.ocsp === false ? + constants.SSL_OP_NO_TICKET : 0, + rejectUnauthorized: false + }, function() { + clientSecure++; + }); + client.on('OCSPResponse', function(resp) { + ocspResponse = resp; + if (resp) + client.destroy(); + }); + client.on('close', function() { + server.close(cb); + }); + }); + + process.on('exit', function() { + if (testOptions.ocsp === false) { + assert.equal(requestCount, clientSecure); + assert.equal(requestCount, 1); + return; + } + + if (testOptions.response) { + assert.equal(ocspResponse.toString(), testOptions.response); + } else { + assert.ok(ocspResponse === null); + } + assert.equal(requestCount, testOptions.response ? 0 : 1); + assert.equal(clientSecure, requestCount); + assert.equal(ocspCount, 1); + }); +} diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js new file mode 100644 index 000000000..9fa82ae3e --- /dev/null +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -0,0 +1,177 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); +var net = require('net'); +var http = require('http'); +var https = require('https'); + +var proxyPort = common.PORT + 1; +var gotRequest = false; + +var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); +var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); + +var options = { + key: key, + cert: cert +}; + +var server = https.createServer(options, function(req, res) { + console.log('SERVER: got request'); + res.writeHead(200, { + 'content-type': 'text/plain' + }); + console.log('SERVER: sending response'); + res.end('hello world\n'); +}); + +var proxy = net.createServer(function(clientSocket) { + console.log('PROXY: got a client connection'); + + var serverSocket = null; + + clientSocket.on('data', function(chunk) { + if (!serverSocket) { + // Verify the CONNECT request + assert.equal('CONNECT localhost:' + common.PORT + ' HTTP/1.1\r\n' + + 'Proxy-Connections: keep-alive\r\n' + + 'Host: localhost:' + proxyPort + '\r\n\r\n', + chunk); + + console.log('PROXY: got CONNECT request'); + console.log('PROXY: creating a tunnel'); + + // create the tunnel + serverSocket = net.connect(common.PORT, function() { + console.log('PROXY: replying to client CONNECT request'); + + // Send the response + clientSocket.write('HTTP/1.1 200 OK\r\nProxy-Connections: keep' + + '-alive\r\nConnections: keep-alive\r\nVia: ' + + 'localhost:' + proxyPort + '\r\n\r\n'); + }); + + serverSocket.on('data', function(chunk) { + clientSocket.write(chunk); + }); + + serverSocket.on('end', function() { + clientSocket.destroy(); + }); + } else { + serverSocket.write(chunk); + } + }); + + clientSocket.on('end', function() { + serverSocket.destroy(); + }); +}); + +server.listen(common.PORT); + +proxy.listen(proxyPort, function() { + console.log('CLIENT: Making CONNECT request'); + + var req = http.request({ + port: proxyPort, + method: 'CONNECT', + path: 'localhost:' + common.PORT, + headers: { + 'Proxy-Connections': 'keep-alive' + } + }); + req.useChunkedEncodingByDefault = false; // for v0.6 + req.on('response', onResponse); // for v0.6 + req.on('upgrade', onUpgrade); // for v0.6 + req.on('connect', onConnect); // for v0.7 or later + req.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, header) { + assert.equal(200, res.statusCode); + console.log('CLIENT: got CONNECT response'); + + // detach the socket + socket.removeAllListeners('data'); + socket.removeAllListeners('close'); + socket.removeAllListeners('error'); + socket.removeAllListeners('drain'); + socket.removeAllListeners('end'); + socket.ondata = null; + socket.onend = null; + socket.ondrain = null; + + console.log('CLIENT: Making HTTPS request'); + + https.get({ + path: '/foo', + key: key, + cert: cert, + socket: socket, // reuse the socket + agent: false, + rejectUnauthorized: false + }, function(res) { + assert.equal(200, res.statusCode); + + res.on('data', function(chunk) { + assert.equal('hello world\n', chunk); + console.log('CLIENT: got HTTPS response'); + gotRequest = true; + }); + + res.on('end', function() { + proxy.close(); + server.close(); + }); + }).on('error', function(er) { + // We're ok with getting ECONNRESET in this test, but it's + // timing-dependent, and thus unreliable. Any other errors + // are just failures, though. + if (er.code !== 'ECONNRESET') + throw er; + }).end(); + } +}); + +process.on('exit', function() { + assert.ok(gotRequest); +}); diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js new file mode 100644 index 000000000..e9a5c5a5d --- /dev/null +++ b/test/parallel/test-tls-passphrase.js @@ -0,0 +1,75 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var key = fs.readFileSync(path.join(common.fixturesDir, 'pass-key.pem')); +var cert = fs.readFileSync(path.join(common.fixturesDir, 'pass-cert.pem')); + +var server = tls.Server({ + key: key, + passphrase: 'passphrase', + cert: cert, + ca: [cert], + requestCert: true, + rejectUnauthorized: true +}, function(s) { + s.end(); +}); + +var connectCount = 0; +server.listen(common.PORT, function() { + var c = tls.connect({ + port: common.PORT, + key: key, + passphrase: 'passphrase', + cert: cert, + rejectUnauthorized: false + }, function() { + ++connectCount; + }); + c.on('end', function() { + server.close(); + }); +}); + +assert.throws(function() { + tls.connect({ + port: common.PORT, + key: key, + passphrase: 'invalid', + cert: cert, + rejectUnauthorized: false + }); +}); + +process.on('exit', function() { + assert.equal(connectCount, 1); +}); diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js new file mode 100644 index 000000000..5eaac8da1 --- /dev/null +++ b/test/parallel/test-tls-pause.js @@ -0,0 +1,92 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var path = require('path'); + +var options = { + key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), + cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) +}; + +var bufSize = 1024 * 1024; +var sent = 0; +var received = 0; + +var server = tls.Server(options, function(socket) { + socket.pipe(socket); + socket.on('data', function(c) { + console.error('data', c.length); + }); +}); + +server.listen(common.PORT, function() { + var resumed = false; + var client = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + console.error('connected'); + client.pause(); + common.debug('paused'); + send(); + function send() { + console.error('sending'); + var ret = client.write(new Buffer(bufSize)); + console.error('write => %j', ret); + if (false !== ret) { + console.error('write again'); + sent += bufSize; + assert.ok(sent < 100 * 1024 * 1024); // max 100MB + return process.nextTick(send); + } + sent += bufSize; + common.debug('sent: ' + sent); + resumed = true; + client.resume(); + console.error('resumed', client); + } + }); + client.on('data', function(data) { + console.error('data'); + assert.ok(resumed); + received += data.length; + console.error('received', received); + console.error('sent', sent); + if (received >= sent) { + common.debug('received: ' + received); + client.end(); + server.close(); + } + }); +}); + +process.on('exit', function() { + assert.equal(sent, received); +}); diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js new file mode 100644 index 000000000..288236a93 --- /dev/null +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var util = require('util'); +var join = require('path').join; +var spawn = require('child_process').spawn; + +var options = { + key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-key.pem')), + cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-cert.pem')), + ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca2-cert.pem')) ] +}; +var verified = false; + +var server = tls.createServer(options, function(cleartext) { + cleartext.end('World'); +}); +server.listen(common.PORT, function() { + var socket = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + var peerCert = socket.getPeerCertificate(); + + common.debug(util.inspect(peerCert)); + assert.equal(peerCert.subject.CN, 'Ádám Lippai'); + verified = true; + server.close(); + }); + socket.end('Hello'); +}); + +process.on('exit', function() { + assert.ok(verified); +}); diff --git a/test/parallel/test-tls-peer-certificate-multi-keys.js b/test/parallel/test-tls-peer-certificate-multi-keys.js new file mode 100644 index 000000000..a321d2cba --- /dev/null +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var util = require('util'); +var join = require('path').join; +var spawn = require('child_process').spawn; + +var options = { + key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), + cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) +}; +var verified = false; + +var server = tls.createServer(options, function(cleartext) { + cleartext.end('World'); +}); +server.listen(common.PORT, function() { + var socket = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + var peerCert = socket.getPeerCertificate(); + common.debug(util.inspect(peerCert)); + assert.deepEqual(peerCert.subject.OU, + ['Information Technology', 'Engineering', 'Marketing']); + verified = true; + server.close(); + }); + socket.end('Hello'); +}); + +process.on('exit', function() { + assert.ok(verified); +}); diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js new file mode 100644 index 000000000..f1d0a7f19 --- /dev/null +++ b/test/parallel/test-tls-peer-certificate.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var util = require('util'); +var join = require('path').join; +var spawn = require('child_process').spawn; + +var options = { + key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-key.pem')), + cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), + ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] +}; +var verified = false; + +var server = tls.createServer(options, function(cleartext) { + cleartext.end('World'); +}); +server.listen(common.PORT, function() { + var socket = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }, function() { + var peerCert = socket.getPeerCertificate(); + assert.ok(!peerCert.issuerCertificate); + + // Verify that detailed return value has all certs + peerCert = socket.getPeerCertificate(true); + assert.ok(peerCert.issuerCertificate); + + common.debug(util.inspect(peerCert)); + assert.equal(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); + assert.equal(peerCert.serialNumber, '9A84ABCFB8A72ABE'); + assert.deepEqual(peerCert.infoAccess['OCSP - URI'], + [ 'http://ocsp.nodejs.org/' ]); + + var issuer = peerCert.issuerCertificate; + assert.ok(issuer.issuerCertificate === issuer); + assert.equal(issuer.serialNumber, 'B5090C899FC2FF93'); + verified = true; + server.close(); + }); + socket.end('Hello'); +}); + +process.on('exit', function() { + assert.ok(verified); +}); diff --git a/test/parallel/test-tls-request-timeout.js b/test/parallel/test-tls-request-timeout.js new file mode 100644 index 000000000..7f46bd213 --- /dev/null +++ b/test/parallel/test-tls-request-timeout.js @@ -0,0 +1,53 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var hadTimeout = false; + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.Server(options, function(socket) { + socket.setTimeout(100); + + socket.on('timeout', function(err) { + hadTimeout = true; + socket.end(); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var socket = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }); +}); + +process.on('exit', function() { + assert.ok(hadTimeout); +}); diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js new file mode 100644 index 000000000..ece965c54 --- /dev/null +++ b/test/parallel/test-tls-securepair-server.js @@ -0,0 +1,153 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); + +var join = require('path').join; +var net = require('net'); +var fs = require('fs'); +var tls = require('tls'); +var spawn = require('child_process').spawn; + +var connections = 0; +var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); +var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); + +function log(a) { + console.error('***server*** ' + a); +} + +var server = net.createServer(function(socket) { + connections++; + log('connection fd=' + socket.fd); + var sslcontext = tls.createSecureContext({key: key, cert: cert}); + sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); + + var pair = tls.createSecurePair(sslcontext, true); + + assert.ok(pair.encrypted.writable); + assert.ok(pair.cleartext.writable); + + pair.encrypted.pipe(socket); + socket.pipe(pair.encrypted); + + log('i set it secure'); + + pair.on('secure', function() { + log('connected+secure!'); + pair.cleartext.write('hello\r\n'); + log(pair.cleartext.getPeerCertificate()); + log(pair.cleartext.getCipher()); + }); + + pair.cleartext.on('data', function(data) { + log('read bytes ' + data.length); + pair.cleartext.write(data); + }); + + socket.on('end', function() { + log('socket end'); + }); + + pair.cleartext.on('error', function(err) { + log('got error: '); + log(err); + log(err.stack); + socket.destroy(); + }); + + pair.encrypted.on('error', function(err) { + log('encrypted error: '); + log(err); + log(err.stack); + socket.destroy(); + }); + + socket.on('error', function(err) { + log('socket error: '); + log(err); + log(err.stack); + socket.destroy(); + }); + + socket.on('close', function(err) { + log('socket closed'); + }); + + pair.on('error', function(err) { + log('secure error: '); + log(err); + log(err.stack); + socket.destroy(); + }); +}); + +var gotHello = false; +var sentWorld = false; +var gotWorld = false; +var opensslExitCode = -1; + +server.listen(common.PORT, function() { + // To test use: openssl s_client -connect localhost:8000 + var client = spawn(common.opensslCli, ['s_client', '-connect', '127.0.0.1:' + + common.PORT]); + + + var out = ''; + + client.stdout.setEncoding('utf8'); + client.stdout.on('data', function(d) { + out += d; + + if (!gotHello && /hello/.test(out)) { + gotHello = true; + client.stdin.write('world\r\n'); + sentWorld = true; + } + + if (!gotWorld && /world/.test(out)) { + gotWorld = true; + client.stdin.end(); + } + }); + + client.stdout.pipe(process.stdout, { end: false }); + + client.on('exit', function(code) { + opensslExitCode = code; + server.close(); + }); +}); + +process.on('exit', function() { + assert.equal(1, connections); + assert.ok(gotHello); + assert.ok(sentWorld); + assert.ok(gotWorld); + assert.equal(0, opensslExitCode); +}); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js new file mode 100644 index 000000000..085749af4 --- /dev/null +++ b/test/parallel/test-tls-server-verify.js @@ -0,0 +1,337 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +// This is a rather complex test which sets up various TLS servers with node +// and connects to them using the 'openssl s_client' command line utility +// with various keys. Depending on the certificate authority and other +// parameters given to the server, the various clients are +// - rejected, +// - accepted and "unauthorized", or +// - accepted and "authorized". + +var testCases = + [{ title: 'Do not request certs. Everyone is unauthorized.', + requestCert: false, + rejectUnauthorized: false, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: false }, + { name: 'agent2', shouldReject: false, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: false }, + { name: 'nocert', shouldReject: false, shouldAuth: false } + ] + }, + + { title: 'Allow both authed and unauthed connections with CA1', + requestCert: true, + rejectUnauthorized: false, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: false, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: false }, + { name: 'nocert', shouldReject: false, shouldAuth: false } + ] + }, + + { title: 'Do not request certs at connection. Do that later', + requestCert: false, + rejectUnauthorized: false, + renegotiate: true, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: false, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: false }, + { name: 'nocert', shouldReject: false, shouldAuth: false } + ] + }, + + { title: 'Allow only authed connections with CA1', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca1-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: true }, + { name: 'agent3', shouldReject: true }, + { name: 'nocert', shouldReject: true } + ] + }, + + { title: 'Allow only authed connections with CA1 and CA2', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca1-cert', 'ca2-cert'], + clients: + [{ name: 'agent1', shouldReject: false, shouldAuth: true }, + { name: 'agent2', shouldReject: true }, + { name: 'agent3', shouldReject: false, shouldAuth: true }, + { name: 'nocert', shouldReject: true } + ] + }, + + + { title: 'Allow only certs signed by CA2 but not in the CRL', + requestCert: true, + rejectUnauthorized: true, + renegotiate: false, + CAs: ['ca2-cert'], + crl: 'ca2-crl', + clients: + [ + { name: 'agent1', shouldReject: true, shouldAuth: false }, + { name: 'agent2', shouldReject: true, shouldAuth: false }, + { name: 'agent3', shouldReject: false, shouldAuth: true }, + // Agent4 has a cert in the CRL. + { name: 'agent4', shouldReject: true, shouldAuth: false }, + { name: 'nocert', shouldReject: true } + ] + } + ]; + + +var constants = require('constants'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var spawn = require('child_process').spawn; + + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + + +var serverKey = loadPEM('agent2-key'); +var serverCert = loadPEM('agent2-cert'); + + +function runClient(options, cb) { + + // Client can connect in three ways: + // - Self-signed cert + // - Certificate, but not signed by CA. + // - Certificate signed by CA. + + var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT]; + + + console.log(' connecting with', options.name); + + switch (options.name) { + case 'agent1': + // Signed by CA1 + args.push('-key'); + args.push(filenamePEM('agent1-key')); + args.push('-cert'); + args.push(filenamePEM('agent1-cert')); + break; + + case 'agent2': + // Self-signed + // This is also the key-cert pair that the server will use. + args.push('-key'); + args.push(filenamePEM('agent2-key')); + args.push('-cert'); + args.push(filenamePEM('agent2-cert')); + break; + + case 'agent3': + // Signed by CA2 + args.push('-key'); + args.push(filenamePEM('agent3-key')); + args.push('-cert'); + args.push(filenamePEM('agent3-cert')); + break; + + case 'agent4': + // Signed by CA2 (rejected by ca2-crl) + args.push('-key'); + args.push(filenamePEM('agent4-key')); + args.push('-cert'); + args.push(filenamePEM('agent4-cert')); + break; + + case 'nocert': + // Do not send certificate + break; + + default: + throw new Error('Unknown agent name'); + } + + // To test use: openssl s_client -connect localhost:8000 + var client = spawn(common.opensslCli, args); + + var out = ''; + + var rejected = true; + var authed = false; + var goodbye = false; + + client.stdout.setEncoding('utf8'); + client.stdout.on('data', function(d) { + out += d; + + if (!goodbye && /_unauthed/g.test(out)) { + console.error(' * unauthed'); + goodbye = true; + client.stdin.end('goodbye\n'); + authed = false; + rejected = false; + } + + if (!goodbye && /_authed/g.test(out)) { + console.error(' * authed'); + goodbye = true; + client.stdin.end('goodbye\n'); + authed = true; + rejected = false; + } + }); + + //client.stdout.pipe(process.stdout); + + client.on('exit', function(code) { + //assert.equal(0, code, options.name + + // ": s_client exited with error code " + code); + if (options.shouldReject) { + assert.equal(true, rejected, options.name + + ' NOT rejected, but should have been'); + } else { + assert.equal(false, rejected, options.name + + ' rejected, but should NOT have been'); + assert.equal(options.shouldAuth, authed); + } + + cb(); + }); +} + + +// Run the tests +var successfulTests = 0; +function runTest(testIndex) { + var tcase = testCases[testIndex]; + if (!tcase) return; + + console.error("Running '%s'", tcase.title); + + var cas = tcase.CAs.map(loadPEM); + + var crl = tcase.crl ? loadPEM(tcase.crl) : null; + + var serverOptions = { + key: serverKey, + cert: serverCert, + ca: cas, + crl: crl, + requestCert: tcase.requestCert, + rejectUnauthorized: tcase.rejectUnauthorized + }; + + var connections = 0; + + /* + * If renegotiating - session might be resumed and openssl won't request + * client's certificate (probably because of bug in the openssl) + */ + if (tcase.renegotiate) { + serverOptions.secureOptions = + constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; + } + + var renegotiated = false; + var server = tls.Server(serverOptions, function handleConnection(c) { + if (tcase.renegotiate && !renegotiated) { + renegotiated = true; + setTimeout(function() { + console.error('- connected, renegotiating'); + c.write('\n_renegotiating\n'); + return c.renegotiate({ + requestCert: true, + rejectUnauthorized: false + }, function(err) { + assert(!err); + c.write('\n_renegotiated\n'); + handleConnection(c); + }); + }, 200); + return; + } + + connections++; + if (c.authorized) { + console.error('- authed connection: ' + + c.getPeerCertificate().subject.CN); + c.write('\n_authed\n'); + } else { + console.error('- unauthed connection: %s', c.authorizationError); + c.write('\n_unauthed\n'); + } + }); + + function runNextClient(clientIndex) { + var options = tcase.clients[clientIndex]; + if (options) { + runClient(options, function() { + runNextClient(clientIndex + 1); + }); + } else { + server.close(); + successfulTests++; + runTest(testIndex + 1); + } + } + + server.listen(common.PORT, function() { + if (tcase.debug) { + console.error('TLS server running on port ' + common.PORT); + } else { + runNextClient(0); + } + }); +} + + +runTest(0); + + +process.on('exit', function() { + assert.equal(successfulTests, testCases.length); +}); diff --git a/test/parallel/test-tls-session-cache.js b/test/parallel/test-tls-session-cache.js new file mode 100644 index 000000000..d5db30ce1 --- /dev/null +++ b/test/parallel/test-tls-session-cache.js @@ -0,0 +1,125 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +doTest({ tickets: false } , function() { + doTest({ tickets: true } , function() { + console.error('all done'); + }); +}); + +function doTest(testOptions, callback) { + var assert = require('assert'); + var tls = require('tls'); + var fs = require('fs'); + var join = require('path').join; + var spawn = require('child_process').spawn; + + var keyFile = join(common.fixturesDir, 'agent.key'); + var certFile = join(common.fixturesDir, 'agent.crt'); + var key = fs.readFileSync(keyFile); + var cert = fs.readFileSync(certFile); + var options = { + key: key, + cert: cert, + ca: [cert], + requestCert: true + }; + var requestCount = 0; + var resumeCount = 0; + var session; + + var server = tls.createServer(options, function(cleartext) { + cleartext.on('error', function(er) { + // We're ok with getting ECONNRESET in this test, but it's + // timing-dependent, and thus unreliable. Any other errors + // are just failures, though. + if (er.code !== 'ECONNRESET') + throw er; + }); + ++requestCount; + cleartext.end(); + }); + server.on('newSession', function(id, data, cb) { + // Emulate asynchronous store + setTimeout(function() { + assert.ok(!session); + session = { + id: id, + data: data + }; + cb(); + }, 1000); + }); + server.on('resumeSession', function(id, callback) { + ++resumeCount; + assert.ok(session); + assert.equal(session.id.toString('hex'), id.toString('hex')); + + // Just to check that async really works there + setTimeout(function() { + callback(null, session.data); + }, 100); + }); + server.listen(common.PORT, function() { + var client = spawn(common.opensslCli, [ + 's_client', + '-tls1', + '-connect', 'localhost:' + common.PORT, + '-servername', 'ohgod', + '-key', join(common.fixturesDir, 'agent.key'), + '-cert', join(common.fixturesDir, 'agent.crt'), + '-reconnect' + ].concat(testOptions.tickets ? [] : '-no_ticket'), { + stdio: [ 0, 1, 'pipe' ] + }); + var err = ''; + client.stderr.setEncoding('utf8'); + client.stderr.on('data', function(chunk) { + err += chunk; + }); + client.on('exit', function(code) { + console.error('done'); + assert.equal(code, 0); + server.close(function() { + setTimeout(callback, 100); + }); + }); + }); + + process.on('exit', function() { + if (testOptions.tickets) { + assert.equal(requestCount, 6); + assert.equal(resumeCount, 0); + } else { + // initial request + reconnect requests (5 times) + assert.ok(session); + assert.equal(requestCount, 6); + assert.equal(resumeCount, 5); + } + }); +} diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js new file mode 100644 index 000000000..1571d5e83 --- /dev/null +++ b/test/parallel/test-tls-set-ciphers.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +var assert = require('assert'); +var exec = require('child_process').exec; +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: 'RC4-MD5' +}; + +var reply = 'I AM THE WALRUS'; // something recognizable +var nconns = 0; +var response = ''; + +process.on('exit', function() { + assert.equal(nconns, 1); + assert.notEqual(response.indexOf(reply), -1); +}); + +var server = tls.createServer(options, function(conn) { + conn.end(reply); + nconns++; +}); + +server.listen(common.PORT, '127.0.0.1', function() { + var cmd = common.opensslCli + ' s_client -cipher ' + options.ciphers + + ' -connect 127.0.0.1:' + common.PORT; + + exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + response = stdout; + server.close(); + }); +}); diff --git a/test/parallel/test-tls-set-encoding.js b/test/parallel/test-tls-set-encoding.js new file mode 100644 index 000000000..0f6beafd1 --- /dev/null +++ b/test/parallel/test-tls-set-encoding.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') +}; + +var connections = 0; +var message = 'hello world\n'; + + +var server = tls.Server(options, function(socket) { + socket.end(message); + connections++; +}); + + +server.listen(common.PORT, function() { + var client = tls.connect({ + port: common.PORT, + rejectUnauthorized: false + }); + + var buffer = ''; + + client.setEncoding('utf8'); + + client.on('data', function(d) { + assert.ok(typeof d === 'string'); + buffer += d; + }); + + + client.on('close', function() { + // readyState is deprecated but we want to make + // sure this isn't triggering an assert in lib/net.js + // See issue #1069. + assert.equal('closed', client.readyState); + + assert.equal(buffer, message); + console.log(message); + server.close(); + }); +}); + + +process.on('exit', function() { + assert.equal(1, connections); +}); diff --git a/test/parallel/test-tls-sni-option.js b/test/parallel/test-tls-sni-option.js new file mode 100644 index 000000000..57c17163a --- /dev/null +++ b/test/parallel/test-tls-sni-option.js @@ -0,0 +1,167 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.features.tls_sni) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} + +var common = require('../common'), + assert = require('assert'), + fs = require('fs'), + tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var serverOptions = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + SNICallback: function(servername, callback) { + var context = SNIContexts[servername]; + + // Just to test asynchronous callback + setTimeout(function() { + if (context) { + if (context.emptyRegression) + callback(null, {}); + else + callback(null, tls.createSecureContext(context)); + } else { + callback(null, null); + } + }, 100); + } +}; + +var SNIContexts = { + 'a.example.com': { + key: loadPEM('agent1-key'), + cert: loadPEM('agent1-cert') + }, + 'b.example.com': { + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert') + }, + 'c.another.com': { + emptyRegression: true + } +}; + +var serverPort = common.PORT; + +var clientsOptions = [{ + port: serverPort, + key: loadPEM('agent1-key'), + cert: loadPEM('agent1-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'a.example.com', + rejectUnauthorized: false +}, { + port: serverPort, + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + ca: [loadPEM('ca2-cert')], + servername: 'b.example.com', + rejectUnauthorized: false +}, { + port: serverPort, + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'c.wrong.com', + rejectUnauthorized: false +}, { + port: serverPort, + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'c.another.com', + rejectUnauthorized: false +}]; + +var serverResults = [], + clientResults = [], + serverErrors = [], + clientErrors = [], + serverError, + clientError; + +var server = tls.createServer(serverOptions, function(c) { + serverResults.push(c.servername); +}); + +server.on('clientError', function(err) { + serverResults.push(null); + serverError = err.message; +}); + +server.listen(serverPort, startTest); + +function startTest() { + function connectClient(i, callback) { + var options = clientsOptions[i]; + clientError = null; + serverError = null; + + var client = tls.connect(options, function() { + clientResults.push( + /Hostname\/IP doesn't/.test(client.authorizationError || '')); + client.destroy(); + + next(); + }); + + client.on('error', function(err) { + clientResults.push(false); + clientError = err.message; + next(); + }); + + function next() { + clientErrors.push(clientError); + serverErrors.push(serverError); + + if (i === clientsOptions.length - 1) + callback(); + else + connectClient(i + 1, callback); + } + }; + + connectClient(0, function() { + server.close(); + }); +} + +process.on('exit', function() { + assert.deepEqual(serverResults, ['a.example.com', 'b.example.com', + 'c.wrong.com', null]); + assert.deepEqual(clientResults, [true, true, false, false]); + assert.deepEqual(clientErrors, [null, null, null, "socket hang up"]); + assert.deepEqual(serverErrors, [null, null, null, "Invalid SNI context"]); +}); diff --git a/test/parallel/test-tls-sni-server-client.js b/test/parallel/test-tls-sni-server-client.js new file mode 100644 index 000000000..31fc41942 --- /dev/null +++ b/test/parallel/test-tls-sni-server-client.js @@ -0,0 +1,130 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +if (!process.features.tls_sni) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} + +var common = require('../common'), + assert = require('assert'), + fs = require('fs'), + tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var serverOptions = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert') +}; + +var SNIContexts = { + 'a.example.com': { + key: loadPEM('agent1-key'), + cert: loadPEM('agent1-cert') + }, + 'asterisk.test.com': { + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert') + } +}; + +var serverPort = common.PORT; + +var clientsOptions = [{ + port: serverPort, + key: loadPEM('agent1-key'), + cert: loadPEM('agent1-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'a.example.com', + rejectUnauthorized: false +}, { + port: serverPort, + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + ca: [loadPEM('ca2-cert')], + servername: 'b.test.com', + rejectUnauthorized: false +}, { + port: serverPort, + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + ca: [loadPEM('ca2-cert')], + servername: 'a.b.test.com', + rejectUnauthorized: false +}, { + port: serverPort, + key: loadPEM('agent3-key'), + cert: loadPEM('agent3-cert'), + ca: [loadPEM('ca1-cert')], + servername: 'c.wrong.com', + rejectUnauthorized: false +}]; + +var serverResults = [], + clientResults = []; + +var server = tls.createServer(serverOptions, function(c) { + serverResults.push(c.servername); +}); + +server.addContext('a.example.com', SNIContexts['a.example.com']); +server.addContext('*.test.com', SNIContexts['asterisk.test.com']); + +server.listen(serverPort, startTest); + +function startTest() { + var i = 0; + function start() { + // No options left + if (i === clientsOptions.length) + return server.close(); + + var options = clientsOptions[i++]; + var client = tls.connect(options, function() { + clientResults.push( + client.authorizationError && + /Hostname\/IP doesn't/.test(client.authorizationError)); + client.destroy(); + + // Continue + start(); + }); + }; + + start(); +} + +process.on('exit', function() { + assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', + 'a.b.test.com', 'c.wrong.com']); + assert.deepEqual(clientResults, [true, true, false, false]); +}); diff --git a/test/parallel/test-tls-ticket-cluster.js b/test/parallel/test-tls-ticket-cluster.js new file mode 100644 index 000000000..22fe10c42 --- /dev/null +++ b/test/parallel/test-tls-ticket-cluster.js @@ -0,0 +1,125 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var tls = require('tls'); +var fs = require('fs'); +var join = require('path').join; + +var workerCount = 4; +var expectedReqCount = 16; + +if (cluster.isMaster) { + var reusedCount = 0; + var reqCount = 0; + var lastSession = null; + var shootOnce = false; + + function shoot() { + console.error('[master] connecting'); + var c = tls.connect(common.PORT, { + session: lastSession, + rejectUnauthorized: false + }, function() { + lastSession = c.getSession(); + c.end(); + + if (++reqCount === expectedReqCount) { + Object.keys(cluster.workers).forEach(function(id) { + cluster.workers[id].send('die'); + }); + } else { + shoot(); + } + }); + } + + function fork() { + var worker = cluster.fork(); + var workerReqCount = 0; + worker.on('message', function(msg) { + console.error('[master] got %j', msg); + if (msg === 'reused') { + ++reusedCount; + } else if (msg === 'listening' && !shootOnce) { + shootOnce = true; + shoot(); + } + }); + + worker.on('exit', function() { + console.error('[master] worker died'); + }); + } + for (var i = 0; i < workerCount; i++) { + fork(); + } + + process.on('exit', function() { + assert.equal(reqCount, expectedReqCount); + assert.equal(reusedCount + 1, reqCount); + }); + return; +} + +var keyFile = join(common.fixturesDir, 'agent.key'); +var certFile = join(common.fixturesDir, 'agent.crt'); +var key = fs.readFileSync(keyFile); +var cert = fs.readFileSync(certFile); +var options = { + key: key, + cert: cert +}; + +var server = tls.createServer(options, function(c) { + if (c.isSessionReused()) { + process.send('reused'); + } else { + process.send('not-reused'); + } + c.end(); +}); + +server.listen(common.PORT, function() { + process.send('listening'); +}); + +process.on('message', function listener(msg) { + console.error('[worker] got %j', msg); + if (msg === 'die') { + server.close(function() { + console.error('[worker] server close'); + + process.exit(); + }); + } +}); + +process.on('exit', function() { + console.error('[worker] exit'); +}); diff --git a/test/parallel/test-tls-ticket.js b/test/parallel/test-tls-ticket.js new file mode 100644 index 000000000..471d8c3ce --- /dev/null +++ b/test/parallel/test-tls-ticket.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var assert = require('assert'); +var fs = require('fs'); +var net = require('net'); +var tls = require('tls'); +var crypto = require('crypto'); + +var common = require('../common'); + +var keys = crypto.randomBytes(48); +var serverLog = []; +var ticketLog = []; + +var serverCount = 0; +function createServer() { + var id = serverCount++; + + var server = tls.createServer({ + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), + ticketKeys: keys + }, function(c) { + serverLog.push(id); + c.end(); + }); + + return server; +} + +var servers = [ createServer(), createServer(), createServer(), createServer(), createServer(), createServer() ]; + +// Create one TCP server and balance sockets to multiple TLS server instances +var shared = net.createServer(function(c) { + servers.shift().emit('connection', c); +}).listen(common.PORT, function() { + start(function() { + shared.close(); + }); +}); + +function start(callback) { + var sess = null; + var left = servers.length; + + function connect() { + var s = tls.connect(common.PORT, { + session: sess, + rejectUnauthorized: false + }, function() { + sess = s.getSession() || sess; + ticketLog.push(s.getTLSTicket().toString('hex')); + }); + s.on('close', function() { + if (--left === 0) + callback(); + else + connect(); + }); + } + + connect(); +} + +process.on('exit', function() { + assert.equal(ticketLog.length, serverLog.length); + for (var i = 0; i < serverLog.length - 1; i++) { + assert.notEqual(serverLog[i], serverLog[i + 1]); + assert.equal(ticketLog[i], ticketLog[i + 1]); + } +}); diff --git a/test/parallel/test-tls-timeout-server-2.js b/test/parallel/test-tls-timeout-server-2.js new file mode 100644 index 000000000..dfa9be3de --- /dev/null +++ b/test/parallel/test-tls-timeout-server-2.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) process.exit(); + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var server = tls.createServer(options, function(cleartext) { + cleartext.setTimeout(50, function() { + cleartext.destroy(); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + tls.connect({ + host: '127.0.0.1', + port: common.PORT, + rejectUnauthorized: false + }); +}); diff --git a/test/parallel/test-tls-timeout-server.js b/test/parallel/test-tls-timeout-server.js new file mode 100644 index 000000000..2c9b973ab --- /dev/null +++ b/test/parallel/test-tls-timeout-server.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) process.exit(); + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var tls = require('tls'); +var fs = require('fs'); + +var clientErrors = 0; + +process.on('exit', function() { + assert.equal(clientErrors, 1); +}); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), + handshakeTimeout: 50 +}; + +var server = tls.createServer(options, assert.fail); + +server.on('clientError', function(err, conn) { + conn.destroy(); + server.close(); + clientErrors++; +}); + +server.listen(common.PORT, function() { + net.connect({ host: '127.0.0.1', port: common.PORT }); +}); diff --git a/test/parallel/test-tls-zero-clear-in.js b/test/parallel/test-tls-zero-clear-in.js new file mode 100644 index 000000000..22f45b663 --- /dev/null +++ b/test/parallel/test-tls-zero-clear-in.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var tls = require('tls'); +var path = require('path'); + +var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); +var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); + +var errorEmitted = false; + +var server = tls.createServer({ + cert: cert, + key: key +}, function(c) { + // Nop + setTimeout(function() { + c.destroy(); + server.close(); + }, 20); +}).listen(common.PORT, function() { + var conn = tls.connect({ + cert: cert, + key: key, + rejectUnauthorized: false, + port: common.PORT + }, function() { + setTimeout(function() { + conn.destroy(); + }, 20); + }); + + // SSL_write() call's return value, when called 0 bytes, should not be + // treated as error. + conn.end(''); + + conn.on('error', function(err) { + console.log(err); + errorEmitted = true; + }); +}); + +process.on('exit', function() { + assert.ok(!errorEmitted); +}); diff --git a/test/parallel/test-tty-stdout-end.js b/test/parallel/test-tty-stdout-end.js new file mode 100644 index 000000000..1fc279068 --- /dev/null +++ b/test/parallel/test-tty-stdout-end.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Can't test this when 'make test' doesn't assign a tty to the stdout. +var common = require('../common'); +var assert = require('assert'); + +var exceptionCaught = false; + +try { + process.stdout.end(); +} catch (e) { + exceptionCaught = true; + assert.ok(common.isError(e)); + assert.equal('process.stdout cannot be closed.', e.message); +} + +assert.ok(exceptionCaught); diff --git a/test/parallel/test-tty-wrap.js b/test/parallel/test-tty-wrap.js new file mode 100644 index 000000000..610b92b43 --- /dev/null +++ b/test/parallel/test-tty-wrap.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TTY = process.binding('tty_wrap').TTY; +var isTTY = process.binding('tty_wrap').isTTY; + +if (isTTY(1) == false) { + console.error('fd 1 is not a tty. skipping test.'); + process.exit(0); +} + +var handle = new TTY(1); +var callbacks = 0; + +var req1 = handle.writeBuffer(Buffer('hello world\n')); +req1.oncomplete = function() { + callbacks++; +}; + +var req2 = handle.writeBuffer(Buffer('hello world\n')); +req2.oncomplete = function() { + callbacks++; +}; + +process.on('exit', function() { + assert.equal(2, callbacks); +}); diff --git a/test/parallel/test-umask.js b/test/parallel/test-umask.js new file mode 100644 index 000000000..a41c46b55 --- /dev/null +++ b/test/parallel/test-umask.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// Note in Windows one can only set the "user" bits. +var mask; +if (process.platform == 'win32') { + mask = '0600'; +} else { + mask = '0664'; +} + +var old = process.umask(mask); + +assert.equal(parseInt(mask, 8), process.umask(old)); + +// confirm reading the umask does not modify it. +// 1. If the test fails, this call will succeed, but the mask will be set to 0 +assert.equal(old, process.umask()); +// 2. If the test fails, process.umask() will return 0 +assert.equal(old, process.umask()); diff --git a/test/parallel/test-url.js b/test/parallel/test-url.js new file mode 100644 index 000000000..f12a00dbe --- /dev/null +++ b/test/parallel/test-url.js @@ -0,0 +1,1625 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var url = require('url'), + util = require('util'); + +// URLs to parse, and expected data +// { url : parsed } +var parseTests = { + '//some_path' : { + 'href': '//some_path', + 'pathname': '//some_path', + 'path': '//some_path' + }, + + 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + path: '/foo.html', + hash: '#h%5Ca%5Cs%5Ch', + href: 'http://evil-phisher/foo.html#h%5Ca%5Cs%5Ch' + }, + + 'http:\\\\evil-phisher\\foo.html?json="\\"foo\\""#h\\a\\s\\h': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + search: '?json=%22%5C%22foo%5C%22%22', + query: 'json=%22%5C%22foo%5C%22%22', + path: '/foo.html?json=%22%5C%22foo%5C%22%22', + hash: '#h%5Ca%5Cs%5Ch', + href: 'http://evil-phisher/foo.html?json=%22%5C%22foo%5C%22%22#h%5Ca%5Cs%5Ch' + }, + + 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h?blarg': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + path: '/foo.html', + hash: '#h%5Ca%5Cs%5Ch?blarg', + href: 'http://evil-phisher/foo.html#h%5Ca%5Cs%5Ch?blarg' + }, + + + 'http:\\\\evil-phisher\\foo.html': { + protocol: 'http:', + slashes: true, + host: 'evil-phisher', + hostname: 'evil-phisher', + pathname: '/foo.html', + path: '/foo.html', + href: 'http://evil-phisher/foo.html' + }, + + 'HTTP://www.example.com/' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'HTTP://www.example.com' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.ExAmPlE.com/' : { + 'href': 'http://www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user:pw@www.ExAmPlE.com/' : { + 'href': 'http://user:pw@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pw', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://USER:PW@www.ExAmPlE.com/' : { + 'href': 'http://USER:PW@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'USER:PW', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user@www.example.com/' : { + 'href': 'http://user@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://user%3Apw@www.example.com/' : { + 'href': 'http://user:pw@www.example.com/', + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pw', + 'host': 'www.example.com', + 'hostname': 'www.example.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://x.com/path?that\'s#all, folks' : { + 'href': 'http://x.com/path?that%27s#all,%20folks', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.com', + 'hostname': 'x.com', + 'search': '?that%27s', + 'query': 'that%27s', + 'pathname': '/path', + 'hash': '#all,%20folks', + 'path': '/path?that%27s' + }, + + 'HTTP://X.COM/Y' : { + 'href': 'http://x.com/Y', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.com', + 'hostname': 'x.com', + 'pathname': '/Y', + 'path': '/Y' + }, + + // + not an invalid host character + // per https://url.spec.whatwg.org/#host-parsing + 'http://x.y.com+a/b/c' : { + 'href': 'http://x.y.com+a/b/c', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com+a', + 'hostname': 'x.y.com+a', + 'pathname': '/b/c', + 'path': '/b/c' + }, + + // an unexpected invalid char in the hostname. + 'HtTp://x.y.cOm;a/b/c?d=e#f gi' : { + 'href': 'http://x.y.com/;a/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com', + 'hostname': 'x.y.com', + 'pathname': ';a/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': ';a/b/c?d=e' + }, + + // make sure that we don't accidentally lcast the path parts. + 'HtTp://x.y.cOm;A/b/c?d=e#f gi' : { + 'href': 'http://x.y.com/;A/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x.y.com', + 'hostname': 'x.y.com', + 'pathname': ';A/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': ';A/b/c?d=e' + }, + + 'http://x...y...#p': { + 'href': 'http://x...y.../#p', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x...y...', + 'hostname': 'x...y...', + 'hash': '#p', + 'pathname': '/', + 'path': '/' + }, + + 'http://x/p/"quoted"': { + 'href': 'http://x/p/%22quoted%22', + 'protocol': 'http:', + 'slashes': true, + 'host': 'x', + 'hostname': 'x', + 'pathname': '/p/%22quoted%22', + 'path': '/p/%22quoted%22' + }, + + ' Is a URL!': { + 'href': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', + 'pathname': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', + 'path': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!' + }, + + 'http://www.narwhaljs.org/blog/categories?id=news' : { + 'href': 'http://www.narwhaljs.org/blog/categories?id=news', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.narwhaljs.org', + 'hostname': 'www.narwhaljs.org', + 'search': '?id=news', + 'query': 'id=news', + 'pathname': '/blog/categories', + 'path': '/blog/categories?id=news' + }, + + 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' : { + 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'hostname': 'mt0.google.com', + 'pathname': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', + 'path': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' : { + 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' + + '&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'hostname': 'mt0.google.com', + 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', + 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', + 'pathname': '/vt/lyrs=m@114', + 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=': + { + 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' + + '&hl=en&src=api&x=2&y=2&z=3&s=', + 'protocol': 'http:', + 'slashes': true, + 'host': 'mt0.google.com', + 'auth': 'user:pass', + 'hostname': 'mt0.google.com', + 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', + 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', + 'pathname': '/vt/lyrs=m@114', + 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' + }, + + 'file:///etc/passwd' : { + 'href': 'file:///etc/passwd', + 'slashes': true, + 'protocol': 'file:', + 'pathname': '/etc/passwd', + 'hostname': '', + 'host': '', + 'path': '/etc/passwd' + }, + + 'file://localhost/etc/passwd' : { + 'href': 'file://localhost/etc/passwd', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/passwd', + 'hostname': 'localhost', + 'host': 'localhost', + 'path': '/etc/passwd' + }, + + 'file://foo/etc/passwd' : { + 'href': 'file://foo/etc/passwd', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/passwd', + 'hostname': 'foo', + 'host': 'foo', + 'path': '/etc/passwd' + }, + + 'file:///etc/node/' : { + 'href': 'file:///etc/node/', + 'slashes': true, + 'protocol': 'file:', + 'pathname': '/etc/node/', + 'hostname': '', + 'host': '', + 'path': '/etc/node/' + }, + + 'file://localhost/etc/node/' : { + 'href': 'file://localhost/etc/node/', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/node/', + 'hostname': 'localhost', + 'host': 'localhost', + 'path': '/etc/node/' + }, + + 'file://foo/etc/node/' : { + 'href': 'file://foo/etc/node/', + 'protocol': 'file:', + 'slashes': true, + 'pathname': '/etc/node/', + 'hostname': 'foo', + 'host': 'foo', + 'path': '/etc/node/' + }, + + 'http:/baz/../foo/bar' : { + 'href': 'http:/baz/../foo/bar', + 'protocol': 'http:', + 'pathname': '/baz/../foo/bar', + 'path': '/baz/../foo/bar' + }, + + 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : { + 'href': 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com:8000', + 'auth': 'user:pass', + 'port': '8000', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : { + 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag', + 'slashes': true, + 'host': 'example.com:8000', + 'auth': 'user:pass', + 'port': '8000', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + '/foo/bar?baz=quux#frag' : { + 'href': '/foo/bar?baz=quux#frag', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + 'http:/foo/bar?baz=quux#frag' : { + 'href': 'http:/foo/bar?baz=quux#frag', + 'protocol': 'http:', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': 'baz=quux', + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + + 'mailto:foo@bar.com?subject=hello' : { + 'href': 'mailto:foo@bar.com?subject=hello', + 'protocol': 'mailto:', + 'host': 'bar.com', + 'auth' : 'foo', + 'hostname' : 'bar.com', + 'search': '?subject=hello', + 'query': 'subject=hello', + 'path': '?subject=hello' + }, + + 'javascript:alert(\'hello\');' : { + 'href': 'javascript:alert(\'hello\');', + 'protocol': 'javascript:', + 'pathname': 'alert(\'hello\');', + 'path': 'alert(\'hello\');' + }, + + 'xmpp:isaacschlueter@jabber.org' : { + 'href': 'xmpp:isaacschlueter@jabber.org', + 'protocol': 'xmpp:', + 'host': 'jabber.org', + 'auth': 'isaacschlueter', + 'hostname': 'jabber.org' + }, + + 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar' : { + 'href' : 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar', + 'protocol' : 'http:', + 'slashes': true, + 'host' : '127.0.0.1:8080', + 'auth' : 'atpass:foo@bar', + 'hostname' : '127.0.0.1', + 'port' : '8080', + 'pathname': '/path', + 'search' : '?search=foo', + 'query' : 'search=foo', + 'hash' : '#bar', + 'path': '/path?search=foo' + }, + + 'svn+ssh://foo/bar': { + 'href': 'svn+ssh://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'svn+ssh:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dash-test://foo/bar': { + 'href': 'dash-test://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dash-test:foo/bar': { + 'href': 'dash-test:foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'path': '/bar' + }, + + 'dot.test://foo/bar': { + 'href': 'dot.test://foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'path': '/bar', + 'slashes': true + }, + + 'dot.test:foo/bar': { + 'href': 'dot.test:foo/bar', + 'host': 'foo', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'path': '/bar' + }, + + // IDNA tests + 'http://www.日本語.com/' : { + 'href': 'http://www.xn--wgv71a119e.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--wgv71a119e.com', + 'hostname': 'www.xn--wgv71a119e.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://example.Bücher.com/' : { + 'href': 'http://example.xn--bcher-kva.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.xn--bcher-kva.com', + 'hostname': 'example.xn--bcher-kva.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.Äffchen.com/' : { + 'href': 'http://www.xn--ffchen-9ta.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--ffchen-9ta.com', + 'hostname': 'www.xn--ffchen-9ta.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://www.Äffchen.cOm;A/b/c?d=e#f gi' : { + 'href': 'http://www.xn--ffchen-9ta.com/;A/b/c?d=e#f%20g%3Ch%3Ei', + 'protocol': 'http:', + 'slashes': true, + 'host': 'www.xn--ffchen-9ta.com', + 'hostname': 'www.xn--ffchen-9ta.com', + 'pathname': ';A/b/c', + 'search': '?d=e', + 'query': 'd=e', + 'hash': '#f%20g%3Ch%3Ei', + 'path': ';A/b/c?d=e' + }, + + 'http://SÉLIER.COM/' : { + 'href': 'http://xn--slier-bsa.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--slier-bsa.com', + 'hostname': 'xn--slier-bsa.com', + 'pathname': '/', + 'path': '/' + }, + + 'http://ليهمابتكلموشعربي؟.ي؟/' : { + 'href': 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', + 'hostname': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', + 'pathname': '/', + 'path': '/' + }, + + 'http://➡.ws/➡' : { + 'href': 'http://xn--hgi.ws/➡', + 'protocol': 'http:', + 'slashes': true, + 'host': 'xn--hgi.ws', + 'hostname': 'xn--hgi.ws', + 'pathname': '/➡', + 'path': '/➡' + }, + + 'http://bucket_name.s3.amazonaws.com/image.jpg': { + protocol: 'http:', + 'slashes': true, + slashes: true, + host: 'bucket_name.s3.amazonaws.com', + hostname: 'bucket_name.s3.amazonaws.com', + pathname: '/image.jpg', + href: 'http://bucket_name.s3.amazonaws.com/image.jpg', + 'path': '/image.jpg' + }, + + 'git+http://github.com/joyent/node.git': { + protocol: 'git+http:', + slashes: true, + host: 'github.com', + hostname: 'github.com', + pathname: '/joyent/node.git', + path: '/joyent/node.git', + href: 'git+http://github.com/joyent/node.git' + }, + + //if local1@domain1 is uses as a relative URL it may + //be parse into auth@hostname, but here there is no + //way to make it work in url.parse, I add the test to be explicit + 'local1@domain1': { + 'pathname': 'local1@domain1', + 'path': 'local1@domain1', + 'href': 'local1@domain1' + }, + + //While this may seem counter-intuitive, a browser will parse + // as a path. + 'www.example.com' : { + 'href': 'www.example.com', + 'pathname': 'www.example.com', + 'path': 'www.example.com' + }, + + // ipv6 support + '[fe80::1]': { + 'href': '[fe80::1]', + 'pathname': '[fe80::1]', + 'path': '[fe80::1]' + }, + + 'coap://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]': { + 'protocol': 'coap:', + 'slashes': true, + 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]', + 'hostname': 'fedc:ba98:7654:3210:fedc:ba98:7654:3210', + 'href': 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/', + 'pathname': '/', + 'path': '/' + }, + + 'coap://[1080:0:0:0:8:800:200C:417A]:61616/': { + 'protocol': 'coap:', + 'slashes': true, + 'host': '[1080:0:0:0:8:800:200c:417a]:61616', + 'port': '61616', + 'hostname': '1080:0:0:0:8:800:200c:417a', + 'href': 'coap://[1080:0:0:0:8:800:200c:417a]:61616/', + 'pathname': '/', + 'path': '/' + }, + + 'http://user:password@[3ffe:2a00:100:7031::1]:8080': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:password', + 'host': '[3ffe:2a00:100:7031::1]:8080', + 'port': '8080', + 'hostname': '3ffe:2a00:100:7031::1', + 'href': 'http://user:password@[3ffe:2a00:100:7031::1]:8080/', + 'pathname': '/', + 'path': '/' + }, + + 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature': { + 'protocol': 'coap:', + 'slashes': true, + 'auth': 'u:p', + 'host': '[::192.9.5.5]:61616', + 'port': '61616', + 'hostname': '::192.9.5.5', + 'href': 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature', + 'search': '?n=Temperature', + 'query': 'n=Temperature', + 'pathname': '/.well-known/r', + 'path': '/.well-known/r?n=Temperature' + }, + + // empty port + 'http://example.com:': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/', + 'pathname': '/', + 'path': '/' + }, + + 'http://example.com:/a/b.html': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/a/b.html', + 'pathname': '/a/b.html', + 'path': '/a/b.html' + }, + + 'http://example.com:?a=b': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/?a=b', + 'search': '?a=b', + 'query': 'a=b', + 'pathname': '/', + 'path': '/?a=b' + }, + + 'http://example.com:#abc': { + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'href': 'http://example.com/#abc', + 'hash': '#abc', + 'pathname': '/', + 'path': '/' + }, + + 'http://[fe80::1]:/a/b?a=b#abc': { + 'protocol': 'http:', + 'slashes': true, + 'host': '[fe80::1]', + 'hostname': 'fe80::1', + 'href': 'http://[fe80::1]/a/b?a=b#abc', + 'search': '?a=b', + 'query': 'a=b', + 'hash': '#abc', + 'pathname': '/a/b', + 'path': '/a/b?a=b' + }, + + 'http://-lovemonsterz.tumblr.com/rss': { + 'protocol': 'http:', + 'slashes': true, + 'host': '-lovemonsterz.tumblr.com', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://-lovemonsterz.tumblr.com/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://-lovemonsterz.tumblr.com:80/rss': { + 'protocol': 'http:', + 'slashes': true, + 'port': '80', + 'host': '-lovemonsterz.tumblr.com:80', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://-lovemonsterz.tumblr.com:80/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://user:pass@-lovemonsterz.tumblr.com/rss': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'host': '-lovemonsterz.tumblr.com', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://user:pass@-lovemonsterz.tumblr.com/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://user:pass@-lovemonsterz.tumblr.com:80/rss': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'port': '80', + 'host': '-lovemonsterz.tumblr.com:80', + 'hostname': '-lovemonsterz.tumblr.com', + 'href': 'http://user:pass@-lovemonsterz.tumblr.com:80/rss', + 'pathname': '/rss', + 'path': '/rss', + }, + + 'http://_jabber._tcp.google.com/test': { + 'protocol': 'http:', + 'slashes': true, + 'host': '_jabber._tcp.google.com', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://_jabber._tcp.google.com/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://user:pass@_jabber._tcp.google.com/test': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'host': '_jabber._tcp.google.com', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://user:pass@_jabber._tcp.google.com/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://_jabber._tcp.google.com:80/test': { + 'protocol': 'http:', + 'slashes': true, + 'port': '80', + 'host': '_jabber._tcp.google.com:80', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://_jabber._tcp.google.com:80/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://user:pass@_jabber._tcp.google.com:80/test': { + 'protocol': 'http:', + 'slashes': true, + 'auth': 'user:pass', + 'port': '80', + 'host': '_jabber._tcp.google.com:80', + 'hostname': '_jabber._tcp.google.com', + 'href': 'http://user:pass@_jabber._tcp.google.com:80/test', + 'pathname': '/test', + 'path': '/test', + }, + + 'http://x:1/\' <>"`/{}|\\^~`/': { + protocol: 'http:', + slashes: true, + host: 'x:1', + port: '1', + hostname: 'x', + pathname: '/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/', + path: '/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/', + href: 'http://x:1/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/' + }, + + 'http://a@b@c/': { + protocol: 'http:', + slashes: true, + auth: 'a@b', + host: 'c', + hostname: 'c', + href: 'http://a%40b@c/', + path: '/', + pathname: '/' + }, + + 'http://a@b?@c': { + protocol: 'http:', + slashes: true, + auth: 'a', + host: 'b', + hostname: 'b', + href: 'http://a@b/?@c', + path: '/?@c', + pathname: '/', + search: '?@c', + query: '@c' + }, + + 'http://a\r" \t\n<\'b:b@c\r\nd/e?f':{ + protocol: 'http:', + slashes: true, + auth: 'a\r" \t\n<\'b:b', + host: 'c', + port: null, + hostname: 'c', + hash: null, + search: '?f', + query: 'f', + pathname: '%0D%0Ad/e', + path: '%0D%0Ad/e?f', + href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f' + } + +}; + +for (var u in parseTests) { + var actual = url.parse(u), + spaced = url.parse(' \t ' + u + '\n\t'); + expected = parseTests[u]; + + Object.keys(actual).forEach(function (i) { + if (expected[i] === undefined && actual[i] === null) { + expected[i] = null; + } + }); + + assert.deepEqual(actual, expected); + assert.deepEqual(spaced, expected); + + var expected = parseTests[u].href, + actual = url.format(parseTests[u]); + + assert.equal(actual, expected, + 'format(' + u + ') == ' + u + '\nactual:' + actual); +} + +var parseTestsWithQueryString = { + '/foo/bar?baz=quux#frag' : { + 'href': '/foo/bar?baz=quux#frag', + 'hash': '#frag', + 'search': '?baz=quux', + 'query': { + 'baz': 'quux' + }, + 'pathname': '/foo/bar', + 'path': '/foo/bar?baz=quux' + }, + 'http://example.com' : { + 'href': 'http://example.com/', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'query': {}, + 'search': '', + 'pathname': '/', + 'path': '/' + }, + '/example': { + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: '', + query: {}, + pathname: '/example', + path: '/example', + href: '/example' + }, + '/example?query=value':{ + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: '?query=value', + query: { query: 'value' }, + pathname: '/example', + path: '/example?query=value', + href: '/example?query=value' + } +}; +for (var u in parseTestsWithQueryString) { + var actual = url.parse(u, true); + var expected = parseTestsWithQueryString[u]; + for (var i in actual) { + if (actual[i] === null && expected[i] === undefined) { + expected[i] = null; + } + } + + assert.deepEqual(actual, expected); +} + +// some extra formatting tests, just to verify +// that it'll format slightly wonky content to a valid url. +var formatTests = { + 'http://example.com?' : { + 'href': 'http://example.com/?', + 'protocol': 'http:', + 'slashes': true, + 'host': 'example.com', + 'hostname': 'example.com', + 'search': '?', + 'query': {}, + 'pathname': '/' + }, + 'http://example.com?foo=bar#frag' : { + 'href': 'http://example.com/?foo=bar#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=bar', + 'query': 'foo=bar', + 'pathname': '/' + }, + 'http://example.com?foo=@bar#frag' : { + 'href': 'http://example.com/?foo=@bar#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=@bar', + 'query': 'foo=@bar', + 'pathname': '/' + }, + 'http://example.com?foo=/bar/#frag' : { + 'href': 'http://example.com/?foo=/bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=/bar/', + 'query': 'foo=/bar/', + 'pathname': '/' + }, + 'http://example.com?foo=?bar/#frag' : { + 'href': 'http://example.com/?foo=?bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag', + 'search': '?foo=?bar/', + 'query': 'foo=?bar/', + 'pathname': '/' + }, + 'http://example.com#frag=?bar/#frag' : { + 'href': 'http://example.com/#frag=?bar/#frag', + 'protocol': 'http:', + 'host': 'example.com', + 'hostname': 'example.com', + 'hash': '#frag=?bar/#frag', + 'pathname': '/' + }, + 'http://google.com" onload="alert(42)/' : { + 'href': 'http://google.com/%22%20onload=%22alert(42)/', + 'protocol': 'http:', + 'host': 'google.com', + 'pathname': '/%22%20onload=%22alert(42)/' + }, + 'http://a.com/a/b/c?s#h' : { + 'href': 'http://a.com/a/b/c?s#h', + 'protocol': 'http', + 'host': 'a.com', + 'pathname': 'a/b/c', + 'hash': 'h', + 'search': 's' + }, + 'xmpp:isaacschlueter@jabber.org' : { + 'href': 'xmpp:isaacschlueter@jabber.org', + 'protocol': 'xmpp:', + 'host': 'jabber.org', + 'auth': 'isaacschlueter', + 'hostname': 'jabber.org' + }, + 'http://atpass:foo%40bar@127.0.0.1/' : { + 'href': 'http://atpass:foo%40bar@127.0.0.1/', + 'auth': 'atpass:foo@bar', + 'hostname': '127.0.0.1', + 'protocol': 'http:', + 'pathname': '/' + }, + 'http://atslash%2F%40:%2F%40@foo/' : { + 'href': 'http://atslash%2F%40:%2F%40@foo/', + 'auth': 'atslash/@:/@', + 'hostname': 'foo', + 'protocol': 'http:', + 'pathname': '/' + }, + 'svn+ssh://foo/bar': { + 'href': 'svn+ssh://foo/bar', + 'hostname': 'foo', + 'protocol': 'svn+ssh:', + 'pathname': '/bar', + 'slashes': true + }, + 'dash-test://foo/bar': { + 'href': 'dash-test://foo/bar', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar', + 'slashes': true + }, + 'dash-test:foo/bar': { + 'href': 'dash-test:foo/bar', + 'hostname': 'foo', + 'protocol': 'dash-test:', + 'pathname': '/bar' + }, + 'dot.test://foo/bar': { + 'href': 'dot.test://foo/bar', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar', + 'slashes': true + }, + 'dot.test:foo/bar': { + 'href': 'dot.test:foo/bar', + 'hostname': 'foo', + 'protocol': 'dot.test:', + 'pathname': '/bar' + }, + // ipv6 support + 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { + 'href': 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', + 'protocol': 'coap:', + 'auth': 'u:p', + 'hostname': '::1', + 'port': '61616', + 'pathname': '/.well-known/r', + 'search': 'n=Temperature' + }, + 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { + 'href': 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', + 'protocol': 'coap', + 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', + 'pathname': '/s/stopButton' + }, + + // encode context-specific delimiters in path and query, but do not touch + // other non-delimiter chars like `%`. + // + + // `#`,`?` in path + '/path/to/%%23%3F+=&.txt?foo=theA1#bar' : { + href: '/path/to/%%23%3F+=&.txt?foo=theA1#bar', + pathname: '/path/to/%#?+=&.txt', + query: { + foo: 'theA1' + }, + hash: "#bar" + }, + + // `#`,`?` in path + `#` in query + '/path/to/%%23%3F+=&.txt?foo=the%231#bar' : { + href: '/path/to/%%23%3F+=&.txt?foo=the%231#bar', + pathname: '/path/to/%#?+=&.txt', + query: { + foo: 'the#1' + }, + hash: "#bar" + }, + + // `?` and `#` in path and search + 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': { + href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag', + protocol: 'http:', + hostname: 'ex.com', + hash: '#frag', + search: '?abc=the#1?&foo=bar', + pathname: '/foo?100%m#r' + }, + + // `?` and `#` in search only + 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': { + href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag', + protocol: 'http:', + hostname: 'ex.com', + hash: '#frag', + search: '?abc=the#1?&foo=bar', + pathname: '/fooA100%mBr' + }, + + // path + 'http://github.com/joyent/node#js1': { + href: 'http://github.com/joyent/node#js1', + protocol: 'http:', + hostname: 'github.com', + hash: '#js1', + path: '/joyent/node' + }, + + // pathname vs. path, path wins + 'http://github.com/joyent/node2#js1': { + href: 'http://github.com/joyent/node2#js1', + protocol: 'http:', + hostname: 'github.com', + hash: '#js1', + path: '/joyent/node2', + pathname: '/joyent/node' + }, + + // pathname with query/search + 'http://github.com/joyent/node?foo=bar#js2': { + href: 'http://github.com/joyent/node?foo=bar#js2', + protocol: 'http:', + hostname: 'github.com', + hash: '#js2', + path: '/joyent/node?foo=bar' + }, + + // path vs. query, path wins + 'http://github.com/joyent/node?foo=bar2#js3': { + href: 'http://github.com/joyent/node?foo=bar2#js3', + protocol: 'http:', + hostname: 'github.com', + hash: '#js3', + path: '/joyent/node?foo=bar2', + query: {foo: 'bar'} + }, + + // path vs. search, path wins + 'http://github.com/joyent/node?foo=bar3#js4': { + href: 'http://github.com/joyent/node?foo=bar3#js4', + protocol: 'http:', + hostname: 'github.com', + hash: '#js4', + path: '/joyent/node?foo=bar3', + search: '?foo=bar' + }, + + // path is present without ? vs. query given + 'http://github.com/joyent/node#js5': { + href: 'http://github.com/joyent/node#js5', + protocol: 'http:', + hostname: 'github.com', + hash: '#js5', + path: '/joyent/node', + query: {foo: 'bar'} + }, + + // path is present without ? vs. search given + 'http://github.com/joyent/node#js6': { + href: 'http://github.com/joyent/node#js6', + protocol: 'http:', + hostname: 'github.com', + hash: '#js6', + path: '/joyent/node', + search: '?foo=bar' + } + +}; +for (var u in formatTests) { + var expect = formatTests[u].href; + delete formatTests[u].href; + var actual = url.format(u); + var actualObj = url.format(formatTests[u]); + assert.equal(actual, expect, + 'wonky format(' + u + ') == ' + expect + + '\nactual:' + actual); + assert.equal(actualObj, expect, + 'wonky format(' + JSON.stringify(formatTests[u]) + + ') == ' + expect + + '\nactual: ' + actualObj); +} + +/* + [from, path, expected] +*/ +var relativeTests = [ + ['/foo/bar/baz', 'quux', '/foo/bar/quux'], + ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], + ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], + ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'], + ['/foo/bar/baz', '/bar', '/bar'], + ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'], + ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'], + ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'], + ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'], + ['foo/bar', '../../../baz', '../../baz'], + ['foo/bar/', '../../../baz', '../baz'], + ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https:/p/a/t/h?s#hash2', + 'https://p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https://u:p@h.com/p/a/t/h?s#hash2', + 'https://u:p@h.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'https:/a/b/c/d', + 'https://a/b/c/d'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:#hash2', + 'http://example.com/b//c//d;p?q#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:/p/a/t/h?s#hash2', + 'http://example.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http://u:p@h.com/p/a/t/h?s#hash2', + 'http://u:p@h.com/p/a/t/h?s#hash2'], + ['http://example.com/b//c//d;p?q#blarg', + 'http:/a/b/c/d', + 'http://example.com/a/b/c/d'], + ['/foo/bar/baz', '/../etc/passwd', '/etc/passwd'] +]; +relativeTests.forEach(function(relativeTest) { + var a = url.resolve(relativeTest[0], relativeTest[1]), + e = relativeTest[2]; + assert.equal(a, e, + 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + + '\n actual=' + a); +}); + + +// https://github.com/joyent/node/issues/568 +[ + undefined, + null, + true, + false, + 0.0, + 0, + [], + {} +].forEach(function(val) { + assert.throws(function() { url.parse(val); }, TypeError); +}); + + +// +// Tests below taken from Chiron +// http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js +// +// Copyright (c) 2002-2008 Kris Kowal +// used with permission under MIT License +// +// Changes marked with @isaacs + +var bases = [ + 'http://a/b/c/d;p?q', + 'http://a/b/c/d;p?q=1/2', + 'http://a/b/c/d;p=1/2?q', + 'fred:///s//a/b/c', + 'http:///s//a/b/c' +]; + +//[to, from, result] +var relativeTests2 = [ + // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html + ['../c', 'foo:a/b', 'foo:c'], + ['foo:.', 'foo:a', 'foo:'], + ['/foo/../../../bar', 'zz:abc', 'zz:/bar'], + ['/foo/../bar', 'zz:abc', 'zz:/bar'], + // @isaacs Disagree. Not how web browsers resolve this. + ['foo/../../../bar', 'zz:abc', 'zz:bar'], + // ['foo/../../../bar', 'zz:abc', 'zz:../../bar'], // @isaacs Added + ['foo/../bar', 'zz:abc', 'zz:bar'], + ['zz:.', 'zz:abc', 'zz:'], + ['/.', bases[0], 'http://a/'], + ['/.foo', bases[0], 'http://a/.foo'], + ['.foo', bases[0], 'http://a/b/c/.foo'], + + // http://gbiv.com/protocols/uri/test/rel_examples1.html + // examples from RFC 2396 + ['g:h', bases[0], 'g:h'], + ['g', bases[0], 'http://a/b/c/g'], + ['./g', bases[0], 'http://a/b/c/g'], + ['g/', bases[0], 'http://a/b/c/g/'], + ['/g', bases[0], 'http://a/g'], + ['//g', bases[0], 'http://g/'], + // changed with RFC 2396bis + //('?y', bases[0], 'http://a/b/c/d;p?y'], + ['?y', bases[0], 'http://a/b/c/d;p?y'], + ['g?y', bases[0], 'http://a/b/c/g?y'], + // changed with RFC 2396bis + //('#s', bases[0], CURRENT_DOC_URI + '#s'], + ['#s', bases[0], 'http://a/b/c/d;p?q#s'], + ['g#s', bases[0], 'http://a/b/c/g#s'], + ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], + [';x', bases[0], 'http://a/b/c/;x'], + ['g;x', bases[0], 'http://a/b/c/g;x'], + ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], + // changed with RFC 2396bis + //('', bases[0], CURRENT_DOC_URI], + ['', bases[0], 'http://a/b/c/d;p?q'], + ['.', bases[0], 'http://a/b/c/'], + ['./', bases[0], 'http://a/b/c/'], + ['..', bases[0], 'http://a/b/'], + ['../', bases[0], 'http://a/b/'], + ['../g', bases[0], 'http://a/b/g'], + ['../..', bases[0], 'http://a/'], + ['../../', bases[0], 'http://a/'], + ['../../g' , bases[0], 'http://a/g'], + ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], + ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], + // changed with RFC 2396bis + //('/./g', bases[0], 'http://a/./g'], + ['/./g', bases[0], 'http://a/g'], + // changed with RFC 2396bis + //('/../g', bases[0], 'http://a/../g'], + ['/../g', bases[0], 'http://a/g'], + ['g.', bases[0], 'http://a/b/c/g.'], + ['.g', bases[0], 'http://a/b/c/.g'], + ['g..', bases[0], 'http://a/b/c/g..'], + ['..g', bases[0], 'http://a/b/c/..g'], + ['./../g', bases[0], 'http://a/b/g'], + ['./g/.', bases[0], 'http://a/b/c/g/'], + ['g/./h', bases[0], 'http://a/b/c/g/h'], + ['g/../h', bases[0], 'http://a/b/c/h'], + ['g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'], + ['g;x=1/../y', bases[0], 'http://a/b/c/y'], + ['g?y/./x', bases[0], 'http://a/b/c/g?y/./x'], + ['g?y/../x', bases[0], 'http://a/b/c/g?y/../x'], + ['g#s/./x', bases[0], 'http://a/b/c/g#s/./x'], + ['g#s/../x', bases[0], 'http://a/b/c/g#s/../x'], + ['http:g', bases[0], ('http:g', 'http://a/b/c/g')], + ['http:', bases[0], ('http:', bases[0])], + // not sure where this one originated + ['/a/b/c/./../../g', bases[0], 'http://a/a/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples2.html + // slashes in base URI's query args + ['g', bases[1], 'http://a/b/c/g'], + ['./g', bases[1], 'http://a/b/c/g'], + ['g/', bases[1], 'http://a/b/c/g/'], + ['/g', bases[1], 'http://a/g'], + ['//g', bases[1], 'http://g/'], + // changed in RFC 2396bis + //('?y', bases[1], 'http://a/b/c/?y'], + ['?y', bases[1], 'http://a/b/c/d;p?y'], + ['g?y', bases[1], 'http://a/b/c/g?y'], + ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], + ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], + ['g#s', bases[1], 'http://a/b/c/g#s'], + ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], + ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], + ['./', bases[1], 'http://a/b/c/'], + ['../', bases[1], 'http://a/b/'], + ['../g', bases[1], 'http://a/b/g'], + ['../../', bases[1], 'http://a/'], + ['../../g' , bases[1], 'http://a/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples3.html + // slashes in path params + // all of these changed in RFC 2396bis + ['g', bases[2], 'http://a/b/c/d;p=1/g'], + ['./g', bases[2], 'http://a/b/c/d;p=1/g'], + ['g/', bases[2], 'http://a/b/c/d;p=1/g/'], + ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'], + [';x', bases[2], 'http://a/b/c/d;p=1/;x'], + ['g;x', bases[2], 'http://a/b/c/d;p=1/g;x'], + ['g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'], + ['g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'], + ['./', bases[2], 'http://a/b/c/d;p=1/'], + ['../', bases[2], 'http://a/b/c/'], + ['../g', bases[2], 'http://a/b/c/g'], + ['../../', bases[2], 'http://a/b/'], + ['../../g' , bases[2], 'http://a/b/g'], + + // http://gbiv.com/protocols/uri/test/rel_examples4.html + // double and triple slash, unknown scheme + ['g:h', bases[3], 'g:h'], + ['g', bases[3], 'fred:///s//a/b/g'], + ['./g', bases[3], 'fred:///s//a/b/g'], + ['g/', bases[3], 'fred:///s//a/b/g/'], + ['/g', bases[3], 'fred:///g'], // may change to fred:///s//a/g + ['//g', bases[3], 'fred://g'], // may change to fred:///s//g + ['//g/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x + ['///g', bases[3], 'fred:///g'], + ['./', bases[3], 'fred:///s//a/b/'], + ['../', bases[3], 'fred:///s//a/'], + ['../g', bases[3], 'fred:///s//a/g'], + + ['../../', bases[3], 'fred:///s//'], + ['../../g' , bases[3], 'fred:///s//g'], + ['../../../g', bases[3], 'fred:///s/g'], + // may change to fred:///s//a/../../../g + ['../../../../g', bases[3], 'fred:///g'], + + // http://gbiv.com/protocols/uri/test/rel_examples5.html + // double and triple slash, well-known scheme + ['g:h', bases[4], 'g:h'], + ['g', bases[4], 'http:///s//a/b/g'], + ['./g', bases[4], 'http:///s//a/b/g'], + ['g/', bases[4], 'http:///s//a/b/g/'], + ['/g', bases[4], 'http:///g'], // may change to http:///s//a/g + ['//g', bases[4], 'http://g/'], // may change to http:///s//g + ['//g/x', bases[4], 'http://g/x'], // may change to http:///s//g/x + ['///g', bases[4], 'http:///g'], + ['./', bases[4], 'http:///s//a/b/'], + ['../', bases[4], 'http:///s//a/'], + ['../g', bases[4], 'http:///s//a/g'], + ['../../', bases[4], 'http:///s//'], + ['../../g' , bases[4], 'http:///s//g'], + // may change to http:///s//a/../../g + ['../../../g', bases[4], 'http:///s/g'], + // may change to http:///s//a/../../../g + ['../../../../g', bases[4], 'http:///g'], + + // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py + ['bar:abc', 'foo:xyz', 'bar:abc'], + ['../abc', 'http://example/x/y/z', 'http://example/x/abc'], + ['http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'], + ['../r', 'http://ex/x/y/z', 'http://ex/x/r'], + ['q/r', 'http://ex/x/y', 'http://ex/x/q/r'], + ['q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'], + ['q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'], + ['ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'], + ['', 'http://ex/x/y', 'http://ex/x/y'], + ['', 'http://ex/x/y/', 'http://ex/x/y/'], + ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'], + ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], + ['#Animal', + 'file:/swap/test/animal.rdf', + 'file:/swap/test/animal.rdf#Animal'], + ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], + ['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'], + ['../r', 'file:/ex/x/y/z', 'file:/ex/x/r'], + ['/r', 'file:/ex/x/y/z', 'file:/r'], + ['q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'], + ['q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'], + ['q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'], + ['q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'], + ['ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'], + ['', 'file:/ex/x/y', 'file:/ex/x/y'], + ['', 'file:/ex/x/y/', 'file:/ex/x/y/'], + ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'], + ['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], + ['file://meetings.example.com/cal#m1', + 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', + 'file://meetings.example.com/cal#m1'], + ['file://meetings.example.com/cal#m1', + 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', + 'file://meetings.example.com/cal#m1'], + ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'], + ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], + // Ryan Lee + ['./', 'http://example/x/abc.efg', 'http://example/x/'], + + + // Graham Klyne's tests + // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls + // 01-31 are from Connelly's cases + + // 32-49 + ['./q:r', 'http://ex/x/y', 'http://ex/x/q:r'], + ['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'], + ['?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'], + ['y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'], + ['local/qual@domain.org#frag', + 'mailto:local', + 'mailto:local/qual@domain.org#frag'], + ['more/qual2@domain2.org#frag', + 'mailto:local/qual1@domain1.org', + 'mailto:local/more/qual2@domain2.org#frag'], + ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'], + ['/x/y?q', 'http://ex?p', 'http://ex/x/y?q'], + ['c/d', 'foo:a/b', 'foo:a/c/d'], + ['/c/d', 'foo:a/b', 'foo:/c/d'], + ['', 'foo:a/b?c#d', 'foo:a/b?c'], + ['b/c', 'foo:a', 'foo:b/c'], + ['../b/c', 'foo:/a/y/z', 'foo:/a/b/c'], + ['./b/c', 'foo:a', 'foo:b/c'], + ['/./b/c', 'foo:a', 'foo:/b/c'], + ['../../d', 'foo://a//b/c', 'foo://a/d'], + ['.', 'foo:a', 'foo:'], + ['..', 'foo:a', 'foo:'], + + // 50-57[cf. TimBL comments -- + // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, + // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) + ['abc', 'http://example/x/y%2Fz', 'http://example/x/abc'], + ['../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'], + ['../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'], + ['abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'], + ['q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'], + ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], + ['/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'], + ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], + + // 70-77 + ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], + ['local2@domain2?query2', + 'mailto:local1@domain1', + 'mailto:local2@domain2?query2'], + ['local2@domain2?query2', + 'mailto:local1@domain1?query1', + 'mailto:local2@domain2?query2'], + ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], + ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], + ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], + ['http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'], + ['http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'], + + // 82-88 + // @isaacs Disagree. Not how browsers do it. + // ['http:this', 'http://example.org/base/uri', 'http:this'], + // @isaacs Added + ['http:this', 'http://example.org/base/uri', 'http://example.org/base/this'], + ['http:this', 'http:base', 'http:this'], + ['.//g', 'f:/a', 'f://g'], + ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], + ['m2@example.ord/c2@example.org', + 'mid:m@example.ord/c@example.org', + 'mid:m@example.ord/m2@example.ord/c2@example.org'], + ['mini1.xml', + 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', + 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'], + ['../b/c', 'foo:a/y/z', 'foo:a/b/c'], + + //changeing auth + ['http://diff:auth@www.example.com', + 'http://asdf:qwer@www.example.com', + 'http://diff:auth@www.example.com/'] +]; +relativeTests2.forEach(function(relativeTest) { + var a = url.resolve(relativeTest[1], relativeTest[0]), + e = relativeTest[2]; + assert.equal(a, e, + 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + + '\n actual=' + a); +}); + +//if format and parse are inverse operations then +//resolveObject(parse(x), y) == parse(resolve(x, y)) + +//host and hostname are special, in this case a '' value is important +var emptyIsImportant = {'host': true, 'hostname': ''}; + +//format: [from, path, expected] +relativeTests.forEach(function(relativeTest) { + var actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]), + expected = url.parse(relativeTest[2]); + + + assert.deepEqual(actual, expected); + + expected = relativeTest[2]; + actual = url.format(actual); + + assert.equal(actual, expected, + 'format(' + actual + ') == ' + expected + '\nactual:' + actual); +}); + +//format: [to, from, result] +// the test: ['.//g', 'f:/a', 'f://g'] is a fundamental problem +// url.parse('f:/a') does not have a host +// url.resolve('f:/a', './/g') does not have a host because you have moved +// down to the g directory. i.e. f: //g, however when this url is parsed +// f:// will indicate that the host is g which is not the case. +// it is unclear to me how to keep this information from being lost +// it may be that a pathname of ////g should collapse to /g but this seems +// to be a lot of work for an edge case. Right now I remove the test +if (relativeTests2[181][0] === './/g' && + relativeTests2[181][1] === 'f:/a' && + relativeTests2[181][2] === 'f://g') { + relativeTests2.splice(181, 1); +} +relativeTests2.forEach(function(relativeTest) { + var actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]), + expected = url.parse(relativeTest[2]); + + assert.deepEqual(actual, expected); + + var expected = relativeTest[2], + actual = url.format(actual); + + assert.equal(actual, expected, + 'format(' + relativeTest[1] + ') == ' + expected + + '\nactual:' + actual); +}); diff --git a/test/parallel/test-utf8-scripts.js b/test/parallel/test-utf8-scripts.js new file mode 100644 index 000000000..4639304f8 --- /dev/null +++ b/test/parallel/test-utf8-scripts.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// üäö + +console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη'); + +assert.equal(true, /Hellö Wörld/.test('Hellö Wörld')); + diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js new file mode 100644 index 000000000..1bea1bf21 --- /dev/null +++ b/test/parallel/test-util-format.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +assert.equal(util.format(), ''); +assert.equal(util.format(''), ''); +assert.equal(util.format([]), '[]'); +assert.equal(util.format({}), '{}'); +assert.equal(util.format(null), 'null'); +assert.equal(util.format(true), 'true'); +assert.equal(util.format(false), 'false'); +assert.equal(util.format('test'), 'test'); + +// CHECKME this is for console.log() compatibility - but is it *right*? +assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); + +assert.equal(util.format('%d', 42.0), '42'); +assert.equal(util.format('%d', 42), '42'); +assert.equal(util.format('%s', 42), '42'); +assert.equal(util.format('%j', 42), '42'); + +assert.equal(util.format('%d', '42.0'), '42'); +assert.equal(util.format('%d', '42'), '42'); +assert.equal(util.format('%s', '42'), '42'); +assert.equal(util.format('%j', '42'), '"42"'); + +assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); + +assert.equal(util.format('%s'), '%s'); +assert.equal(util.format('%s', undefined), 'undefined'); +assert.equal(util.format('%s', 'foo'), 'foo'); +assert.equal(util.format('%s:%s'), '%s:%s'); +assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); +assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); +assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); +assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); +assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); +assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); + +(function() { + var o = {}; + o.o = o; + assert.equal(util.format('%j', o), '[Circular]'); +})(); + +// Errors +assert.equal(util.format(new Error('foo')), '[Error: foo]'); +function CustomError(msg) { + Error.call(this); + Object.defineProperty(this, 'message', { value: msg, enumerable: false }); + Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); +} +util.inherits(CustomError, Error); +assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js new file mode 100644 index 000000000..2a7c2c4fc --- /dev/null +++ b/test/parallel/test-util-inspect.js @@ -0,0 +1,246 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); + +// test the internal isDate implementation +var Date2 = require('vm').runInNewContext('Date'); +var d = new Date2(); +var orig = util.inspect(d); +Date2.prototype.foo = 'bar'; +var after = util.inspect(d); +assert.equal(orig, after); + +// test positive/negative zero +assert.equal(util.inspect(0), '0'); +assert.equal(util.inspect(-0), '-0'); + +// test for sparse array +var a = ['foo', 'bar', 'baz']; +assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); +delete a[1]; +assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); +assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); +assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); + +// test for property descriptors +var getter = Object.create(null, { + a: { + get: function() { return 'aaa'; } + } +}); +var setter = Object.create(null, { + b: { + set: function() {} + } +}); +var getterAndSetter = Object.create(null, { + c: { + get: function() { return 'ccc'; }, + set: function() {} + } +}); +assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); +assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); +assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); + +// exceptions should print the error message, not '{}' +assert.equal(util.inspect(new Error()), '[Error]'); +assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); +assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); +assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); +try { + undef(); +} catch (e) { + assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); +} +var ex = util.inspect(new Error('FAIL'), true); +assert.ok(ex.indexOf('[Error: FAIL]') != -1); +assert.ok(ex.indexOf('[stack]') != -1); +assert.ok(ex.indexOf('[message]') != -1); + +// GH-1941 +// should not throw: +assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); + +// GH-1944 +assert.doesNotThrow(function() { + var d = new Date(); + d.toUTCString = null; + util.inspect(d); +}); + +assert.doesNotThrow(function() { + var r = /regexp/; + r.toString = null; + util.inspect(r); +}); + +// bug with user-supplied inspect function returns non-string +assert.doesNotThrow(function() { + util.inspect([{ + inspect: function() { return 123; } + }]); +}); + +// GH-2225 +var x = { inspect: util.inspect }; +assert.ok(util.inspect(x).indexOf('inspect') != -1); + +// util.inspect should not display the escaped value of a key. +var w = { + '\\': 1, + '\\\\': 2, + '\\\\\\': 3, + '\\\\\\\\': 4, +} + +var y = ['a', 'b', 'c']; +y['\\\\\\'] = 'd'; + +assert.ok(util.inspect(w), + '{ \'\\\': 1, \'\\\\\': 2, \'\\\\\\\': 3, \'\\\\\\\\\': 4 }'); +assert.ok(util.inspect(y), '[ \'a\', \'b\', \'c\', \'\\\\\\\': \'d\' ]'); + +// util.inspect.styles and util.inspect.colors +function test_color_style(style, input, implicit) { + var color_name = util.inspect.styles[style]; + var color = ['', '']; + if(util.inspect.colors[color_name]) + color = util.inspect.colors[color_name]; + + var without_color = util.inspect(input, false, 0, false); + var with_color = util.inspect(input, false, 0, true); + var expect = '\u001b[' + color[0] + 'm' + without_color + + '\u001b[' + color[1] + 'm'; + assert.equal(with_color, expect, 'util.inspect color for style '+style); +} + +test_color_style('special', function(){}); +test_color_style('number', 123.456); +test_color_style('boolean', true); +test_color_style('undefined', undefined); +test_color_style('null', null); +test_color_style('string', 'test string'); +test_color_style('date', new Date); +test_color_style('regexp', /regexp/); + +// an object with "hasOwnProperty" overwritten should not throw +assert.doesNotThrow(function() { + util.inspect({ + hasOwnProperty: null + }); +}); + +// new API, accepts an "options" object +var subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; +Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); + +assert(util.inspect(subject, { showHidden: false }).indexOf('hidden') === -1); +assert(util.inspect(subject, { showHidden: true }).indexOf('hidden') !== -1); +assert(util.inspect(subject, { colors: false }).indexOf('\u001b[32m') === -1); +assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1); +assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1); +assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1); +assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); + +// "customInspect" option can enable/disable calling inspect() on objects +subject = { inspect: function() { return 123; } }; + +assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); +assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); +assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); +assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); + +// custom inspect() functions should be able to return other Objects +subject.inspect = function() { return { foo: 'bar' }; }; + +assert.equal(util.inspect(subject), '{ foo: \'bar\' }'); + +subject.inspect = function(depth, opts) { + assert.strictEqual(opts.customInspectOptions, true); +}; + +util.inspect(subject, { customInspectOptions: true }); + +// util.inspect with "colors" option should produce as many lines as without it +function test_lines(input) { + var count_lines = function(str) { + return (str.match(/\n/g) || []).length; + } + + var without_color = util.inspect(input); + var with_color = util.inspect(input, {colors: true}); + assert.equal(count_lines(without_color), count_lines(with_color)); +} + +test_lines([1, 2, 3, 4, 5, 6, 7]); +test_lines(function() { + var big_array = []; + for (var i = 0; i < 100; i++) { + big_array.push(i); + } + return big_array; +}()); +test_lines({foo: 'bar', baz: 35, b: {a: 35}}); +test_lines({ + foo: 'bar', + baz: 35, + b: {a: 35}, + very_long_key: 'very_long_value', + even_longer_key: ['with even longer value in array'] +}); + +// test boxed primitives output the correct values +assert.equal(util.inspect(new String('test')), '[String: \'test\']'); +assert.equal(util.inspect(new Boolean(false)), '[Boolean: false]'); +assert.equal(util.inspect(new Boolean(true)), '[Boolean: true]'); +assert.equal(util.inspect(new Number(0)), '[Number: 0]'); +assert.equal(util.inspect(new Number(-0)), '[Number: -0]'); +assert.equal(util.inspect(new Number(-1.1)), '[Number: -1.1]'); +assert.equal(util.inspect(new Number(13.37)), '[Number: 13.37]'); + +// test boxed primitives with own properties +var str = new String('baz'); +str.foo = 'bar'; +assert.equal(util.inspect(str), '{ [String: \'baz\'] foo: \'bar\' }'); + +var bool = new Boolean(true); +bool.foo = 'bar'; +assert.equal(util.inspect(bool), '{ [Boolean: true] foo: \'bar\' }'); + +var num = new Number(13.37); +num.foo = 'bar'; +assert.equal(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }'); + +// test es6 Symbol +if (typeof Symbol !== 'undefined') { + assert.equal(util.inspect(Symbol()), 'Symbol()'); + assert.equal(util.inspect(Symbol(123)), 'Symbol(123)'); + assert.equal(util.inspect(Symbol('hi')), 'Symbol(hi)'); + assert.equal(util.inspect([Symbol()]), '[ Symbol() ]'); + assert.equal(util.inspect({ foo: Symbol() }), '{ foo: Symbol() }'); +} diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js new file mode 100644 index 000000000..1912c69f8 --- /dev/null +++ b/test/parallel/test-util-log.js @@ -0,0 +1,58 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var assert = require('assert'); +var util = require('util'); + +assert.ok(process.stdout.writable); +assert.ok(process.stderr.writable); + +var stdout_write = global.process.stdout.write; +var strings = []; +global.process.stdout.write = function(string) { + strings.push(string); +}; +console._stderr = process.stdout; + +var tests = [ + {input: 'foo', output: 'foo'}, + {input: undefined, output: 'undefined'}, + {input: null, output: 'null'}, + {input: false, output: 'false'}, + {input: 42, output: '42'}, + {input: function(){}, output: '[Function]'}, + {input: parseInt('not a number', 10), output: 'NaN'}, + {input: {answer: 42}, output: '{ answer: 42 }'}, + {input: [1,2,3], output: '[ 1, 2, 3 ]'} +]; + +// test util.log() +tests.forEach(function(test) { + util.log(test.input); + var result = strings.shift().trim(), + re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/), + match = re.exec(result); + assert.ok(match); + assert.equal(match[1], test.output); +}); + +global.process.stdout.write = stdout_write; diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js new file mode 100644 index 000000000..4e75d512c --- /dev/null +++ b/test/parallel/test-util.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var context = require('vm').runInNewContext; + +// isArray +assert.equal(true, util.isArray([])); +assert.equal(true, util.isArray(Array())); +assert.equal(true, util.isArray(new Array())); +assert.equal(true, util.isArray(new Array(5))); +assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); +assert.equal(true, util.isArray(context('Array')())); +assert.equal(false, util.isArray({})); +assert.equal(false, util.isArray({ push: function() {} })); +assert.equal(false, util.isArray(/regexp/)); +assert.equal(false, util.isArray(new Error)); +assert.equal(false, util.isArray(Object.create(Array.prototype))); + +// isRegExp +assert.equal(true, util.isRegExp(/regexp/)); +assert.equal(true, util.isRegExp(RegExp())); +assert.equal(true, util.isRegExp(new RegExp())); +assert.equal(true, util.isRegExp(context('RegExp')())); +assert.equal(false, util.isRegExp({})); +assert.equal(false, util.isRegExp([])); +assert.equal(false, util.isRegExp(new Date())); +assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); + +// isDate +assert.equal(true, util.isDate(new Date())); +assert.equal(true, util.isDate(new Date(0))); +assert.equal(true, util.isDate(new (context('Date')))); +assert.equal(false, util.isDate(Date())); +assert.equal(false, util.isDate({})); +assert.equal(false, util.isDate([])); +assert.equal(false, util.isDate(new Error)); +assert.equal(false, util.isDate(Object.create(Date.prototype))); + +// isError +assert.equal(true, util.isError(new Error)); +assert.equal(true, util.isError(new TypeError)); +assert.equal(true, util.isError(new SyntaxError)); +assert.equal(true, util.isError(new (context('Error')))); +assert.equal(true, util.isError(new (context('TypeError')))); +assert.equal(true, util.isError(new (context('SyntaxError')))); +assert.equal(false, util.isError({})); +assert.equal(false, util.isError({ name: 'Error', message: '' })); +assert.equal(false, util.isError([])); +assert.equal(true, util.isError(Object.create(Error.prototype))); + +// isObject +assert.ok(util.isObject({}) === true); + +// _extend +assert.deepEqual(util._extend({a:1}), {a:1}); +assert.deepEqual(util._extend({a:1}, []), {a:1}); +assert.deepEqual(util._extend({a:1}, null), {a:1}); +assert.deepEqual(util._extend({a:1}, true), {a:1}); +assert.deepEqual(util._extend({a:1}, false), {a:1}); +assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); +assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); diff --git a/test/parallel/test-v8-flags.js b/test/parallel/test-v8-flags.js new file mode 100644 index 000000000..1397d8bed --- /dev/null +++ b/test/parallel/test-v8-flags.js @@ -0,0 +1,26 @@ +// Copyright (c) 2014, StrongLoop Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var v8 = require('v8'); +var vm = require('vm'); + +v8.setFlagsFromString('--allow_natives_syntax'); +assert(eval('%_IsSmi(42)')); +assert(vm.runInThisContext('%_IsSmi(42)')); + +v8.setFlagsFromString('--noallow_natives_syntax'); +assert.throws(function() { eval('%_IsSmi(42)') }, SyntaxError); +assert.throws(function() { vm.runInThisContext('%_IsSmi(42)') }, SyntaxError); diff --git a/test/parallel/test-v8-gc.js b/test/parallel/test-v8-gc.js new file mode 100644 index 000000000..4bce8099d --- /dev/null +++ b/test/parallel/test-v8-gc.js @@ -0,0 +1,46 @@ +// Copyright (c) 2014, StrongLoop Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// Flags: --expose_gc + +var common = require('../common'); +var assert = require('assert'); +var v8 = require('v8'); + +assert(typeof gc === 'function', 'Run this test with --expose_gc.'); + +var ncalls = 0; +var before; +var after; + +function ongc(before_, after_) { + // Try very hard to not create garbage because that could kick off another + // garbage collection cycle. + before = before_; + after = after_; + ncalls += 1; +} + +gc(); +v8.on('gc', ongc); +gc(); +v8.removeListener('gc', ongc); +gc(); + +assert.equal(ncalls, 1); +assert.equal(typeof before, 'object'); +assert.equal(typeof after, 'object'); +assert.equal(typeof before.timestamp, 'number'); +assert.equal(typeof after.timestamp, 'number'); +assert.equal(before.timestamp <= after.timestamp, true); diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js new file mode 100644 index 000000000..d4623363a --- /dev/null +++ b/test/parallel/test-v8-stats.js @@ -0,0 +1,29 @@ +// Copyright (c) 2014, StrongLoop Inc. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var v8 = require('v8'); + +var s = v8.getHeapStatistics(); +var keys = [ + 'heap_size_limit', + 'total_heap_size', + 'total_heap_size_executable', + 'total_physical_size', + 'used_heap_size']; +assert.deepEqual(Object.keys(s).sort(), keys); +keys.forEach(function(key) { + assert.equal(typeof s[key], 'number'); +}); diff --git a/test/parallel/test-vm-basic.js b/test/parallel/test-vm-basic.js new file mode 100644 index 000000000..680a81a4b --- /dev/null +++ b/test/parallel/test-vm-basic.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +// Test 1: vm.runInNewContext +var sandbox = {}; +var result = vm.runInNewContext( + 'foo = "bar"; this.typeofProcess = typeof process; typeof Object;', + sandbox +); +assert.deepEqual(sandbox, { + foo: 'bar', + typeofProcess: 'undefined', +}); +assert.strictEqual(result, 'function'); + +// Test 2: vm.runInContext +var sandbox2 = { foo: 'bar' }; +var context = vm.createContext(sandbox2); +var result = vm.runInContext( + 'baz = foo; this.typeofProcess = typeof process; typeof Object;', + context +); +assert.deepEqual(sandbox2, { + foo: 'bar', + baz: 'bar', + typeofProcess: 'undefined' +}); +assert.strictEqual(result, 'function'); + +// Test 3: vm.runInThisContext +var result = vm.runInThisContext( + 'vmResult = "foo"; Object.prototype.toString.call(process);' +); +assert.strictEqual(global.vmResult, 'foo'); +assert.strictEqual(result, '[object process]'); +delete global.vmResult; + +// Test 4: vm.runInNewContext +var result = vm.runInNewContext( + 'vmResult = "foo"; typeof process;' +); +assert.strictEqual(global.vmResult, undefined); +assert.strictEqual(result, 'undefined'); + +// Test 5: vm.createContext +var sandbox3 = {}; +var context2 = vm.createContext(sandbox3); +assert.strictEqual(sandbox3, context2); diff --git a/test/parallel/test-vm-context-async-script.js b/test/parallel/test-vm-context-async-script.js new file mode 100644 index 000000000..d201e98eb --- /dev/null +++ b/test/parallel/test-vm-context-async-script.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var sandbox = { setTimeout: setTimeout }; + +var ctx = vm.createContext(sandbox); + +vm.runInContext('setTimeout(function() { x = 3; }, 0);', ctx); +setTimeout(function () { + assert.strictEqual(sandbox.x, 3); + assert.strictEqual(ctx.x, 3); +}, 1); diff --git a/test/parallel/test-vm-context-property-forwarding.js b/test/parallel/test-vm-context-property-forwarding.js new file mode 100644 index 000000000..6d51463ad --- /dev/null +++ b/test/parallel/test-vm-context-property-forwarding.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var sandbox = { x: 3 }; + +var ctx = vm.createContext(sandbox); + +assert.strictEqual(vm.runInContext('x;', ctx), 3); +vm.runInContext('y = 4;', ctx); +assert.strictEqual(sandbox.y, 4); +assert.strictEqual(ctx.y, 4); diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js new file mode 100644 index 000000000..c843addc6 --- /dev/null +++ b/test/parallel/test-vm-context.js @@ -0,0 +1,82 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var vm = require('vm'); +var Script = vm.Script; +var script = new Script('"passed";'); + +console.error('run in a new empty context'); +var context = vm.createContext(); +var result = script.runInContext(context); +assert.equal('passed', result); + +console.error('create a new pre-populated context'); +context = vm.createContext({'foo': 'bar', 'thing': 'lala'}); +assert.equal('bar', context.foo); +assert.equal('lala', context.thing); + +console.error('test updating context'); +script = new Script('foo = 3;'); +result = script.runInContext(context); +assert.equal(3, context.foo); +assert.equal('lala', context.thing); + +// Issue GH-227: +assert.throws(function () { + vm.runInNewContext('', null, 'some.js'); +}, TypeError); + +// Issue GH-1140: +console.error('test runInContext signature'); +var gh1140Exception; +try { + vm.runInContext('throw new Error()', context, 'expected-filename.js'); +} +catch (e) { + gh1140Exception = e; + assert.ok(/expected-filename/.test(e.stack), + 'expected appearance of filename in Error stack'); +} +assert.ok(gh1140Exception, + 'expected exception from runInContext signature test'); + +// GH-558, non-context argument segfaults / raises assertion +[undefined, null, 0, 0.0, '', {}, []].forEach(function(e) { + assert.throws(function() { script.runInContext(e); }, TypeError); + assert.throws(function() { vm.runInContext('', e); }, TypeError); +}); + +// Issue GH-693: +console.error('test RegExp as argument to assert.throws'); +script = vm.createScript('var assert = require(\'assert\'); assert.throws(' + + 'function() { throw "hello world"; }, /hello/);', + 'some.js'); +script.runInNewContext({ require : require }); + +// Issue GH-7529 +script = vm.createScript('delete b'); +var ctx = {}; +Object.defineProperty(ctx, 'b', { configurable: false }); +ctx = vm.createContext(ctx); +assert.equal(script.runInContext(ctx), false); diff --git a/test/parallel/test-vm-create-and-run-in-context.js b/test/parallel/test-vm-create-and-run-in-context.js new file mode 100644 index 000000000..863569ce7 --- /dev/null +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var vm = require('vm'); + +console.error('run in a new empty context'); +var context = vm.createContext(); +var result = vm.runInContext('"passed";', context); +assert.equal('passed', result); + +console.error('create a new pre-populated context'); +context = vm.createContext({'foo': 'bar', 'thing': 'lala'}); +assert.equal('bar', context.foo); +assert.equal('lala', context.thing); + +console.error('test updating context'); +result = vm.runInContext('var foo = 3;', context); +assert.equal(3, context.foo); +assert.equal('lala', context.thing); diff --git a/test/parallel/test-vm-create-context-accessors.js b/test/parallel/test-vm-create-context-accessors.js new file mode 100644 index 000000000..f0622245b --- /dev/null +++ b/test/parallel/test-vm-create-context-accessors.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var ctx = {}; + +Object.defineProperty(ctx, 'getter', { + get: function() { + return 'ok'; + } +}); + +var val; +Object.defineProperty(ctx, 'setter', { + set: function(_val) { + val = _val; + }, + get: function() { + return 'ok=' + val; + } +}); + +ctx = vm.createContext(ctx); + +var result = vm.runInContext('setter = "test";[getter,setter]', ctx); +assert.deepEqual(result, ['ok', 'ok=test']); diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js new file mode 100644 index 000000000..8c49a3736 --- /dev/null +++ b/test/parallel/test-vm-create-context-arg.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +assert.throws(function() { + var ctx = vm.createContext('string is not supported'); +}, TypeError); + +assert.doesNotThrow(function() { + var ctx = vm.createContext({ a: 1 }); + ctx = vm.createContext([0, 1, 2, 3]); +}); + +assert.doesNotThrow(function() { + var sandbox = {}; + vm.createContext(sandbox); + vm.createContext(sandbox); +}); diff --git a/test/parallel/test-vm-create-context-circular-reference.js b/test/parallel/test-vm-create-context-circular-reference.js new file mode 100644 index 000000000..ae5b48c81 --- /dev/null +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -0,0 +1,34 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var sbx = {}; +sbx.window = sbx; + +sbx = vm.createContext(sbx); + +sbx.test = 123; + +assert.equal(sbx.window.window.window.window.window.test, 123); + diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js new file mode 100644 index 000000000..6f5d501fe --- /dev/null +++ b/test/parallel/test-vm-cross-context.js @@ -0,0 +1,30 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var vm = require('vm'); +var ctx = vm.createContext(global); + +assert.doesNotThrow(function() { + vm.runInContext("!function() { var x = console.log; }()", ctx); +}); diff --git a/test/parallel/test-vm-debug-context.js b/test/parallel/test-vm-debug-context.js new file mode 100644 index 000000000..5569b3853 --- /dev/null +++ b/test/parallel/test-vm-debug-context.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +assert.throws(function() { + vm.runInDebugContext('*'); +}, /SyntaxError/); + +assert.throws(function() { + vm.runInDebugContext({ toString: assert.fail }); +}, /AssertionError/); + +assert.throws(function() { + vm.runInDebugContext('throw URIError("BAM")'); +}, /URIError/); + +assert.throws(function() { + vm.runInDebugContext('(function(f) { f(f) })(function(f) { f(f) })'); +}, /RangeError/); + +assert.equal(typeof(vm.runInDebugContext('this')), 'object'); +assert.equal(typeof(vm.runInDebugContext('Debug')), 'object'); + +assert.strictEqual(vm.runInDebugContext(), undefined); +assert.strictEqual(vm.runInDebugContext(0), 0); +assert.strictEqual(vm.runInDebugContext(null), null); +assert.strictEqual(vm.runInDebugContext(undefined), undefined); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js new file mode 100644 index 000000000..58772ba2f --- /dev/null +++ b/test/parallel/test-vm-function-declaration.js @@ -0,0 +1,47 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var vm = require('vm'); +var o = vm.createContext({ console: console }); + +// This triggers the setter callback in node_contextify.cc +var code = 'var a = function() {};\n'; + +// but this does not, since function decls are defineProperties, +// not simple sets. +code += 'function b(){}\n'; + +// Grab the global b function as the completion value, to ensure that +// we are getting the global function, and not some other thing +code += '(function(){return this})().b;\n' + +var res = vm.runInContext(code, o, 'test'); + +assert.equal(typeof res, 'function', 'result should be function'); +assert.equal(res.name, 'b', 'res should be named b'); +assert.equal(typeof o.a, 'function', 'a should be function'); +assert.equal(typeof o.b, 'function', 'b should be function'); +assert.equal(res, o.b, 'result should be global b function'); + +console.log('ok'); diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js new file mode 100644 index 000000000..fcfe489c1 --- /dev/null +++ b/test/parallel/test-vm-global-define-property.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var vm = require('vm'); + +var code = + 'Object.defineProperty(this, "f", {\n' + + ' get: function() { return x; },\n' + + ' set: function(k) { x = k; },\n' + + ' configurable: true,\n' + + ' enumerable: true\n' + + '});\n' + + 'g = f;\n' + + 'f;\n'; + +var x = {}; +var o = vm.createContext({ console: console, x: x }); + +var res = vm.runInContext(code, o, 'test'); + +assert(res); +assert.equal(typeof res, 'object'); +assert.equal(res, x); +assert.equal(o.f, res); +assert.deepEqual(Object.keys(o), ['console', 'x', 'g', 'f']); diff --git a/test/parallel/test-vm-global-identity.js b/test/parallel/test-vm-global-identity.js new file mode 100644 index 000000000..adfb32358 --- /dev/null +++ b/test/parallel/test-vm-global-identity.js @@ -0,0 +1,31 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +var ctx = vm.createContext(); +ctx.window = ctx; + +var thisVal = vm.runInContext('this;', ctx); +var windowVal = vm.runInContext('window;', ctx); +assert.strictEqual(thisVal, windowVal); diff --git a/test/parallel/test-vm-harmony-proxies.js b/test/parallel/test-vm-harmony-proxies.js new file mode 100644 index 000000000..e1b4ec8ad --- /dev/null +++ b/test/parallel/test-vm-harmony-proxies.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Flags: --harmony_proxies + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +// src/node_contextify.cc filters out the Proxy object from the parent +// context. Make sure that the new context has a Proxy object of its own. +var sandbox = {}; +var result = vm.runInNewContext('this.Proxy = Proxy', sandbox); +assert(typeof sandbox.Proxy === 'object'); +assert(sandbox.Proxy !== Proxy); + +// Unless we copy the Proxy object explicitly, of course. +var sandbox = { Proxy: Proxy }; +var result = vm.runInNewContext('this.Proxy = Proxy', sandbox); +assert(typeof sandbox.Proxy === 'object'); +assert(sandbox.Proxy === Proxy); diff --git a/test/parallel/test-vm-harmony-symbols.js b/test/parallel/test-vm-harmony-symbols.js new file mode 100644 index 000000000..200084fdf --- /dev/null +++ b/test/parallel/test-vm-harmony-symbols.js @@ -0,0 +1,36 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +// The sandbox should have its own Symbol constructor. +var sandbox = {}; +var result = vm.runInNewContext('this.Symbol = Symbol', sandbox); +assert(typeof sandbox.Symbol === 'function'); +assert(sandbox.Symbol !== Symbol); + +// Unless we copy the Symbol constructor explicitly, of course. +var sandbox = { Symbol: Symbol }; +var result = vm.runInNewContext('this.Symbol = Symbol', sandbox); +assert(typeof sandbox.Symbol === 'function'); +assert(sandbox.Symbol === Symbol); diff --git a/test/parallel/test-vm-is-context.js b/test/parallel/test-vm-is-context.js new file mode 100644 index 000000000..9ef2037fe --- /dev/null +++ b/test/parallel/test-vm-is-context.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +assert.throws(function() { + vm.isContext('string is not supported'); +}, TypeError); + +assert.strictEqual(vm.isContext({}), false); +assert.strictEqual(vm.isContext([]), false); + +assert.strictEqual(vm.isContext(vm.createContext()), true); +assert.strictEqual(vm.isContext(vm.createContext([])), true); + +var sandbox = { foo: 'bar' }; +vm.createContext(sandbox); +assert.strictEqual(vm.isContext(sandbox), true); diff --git a/test/parallel/test-vm-new-script-new-context.js b/test/parallel/test-vm-new-script-new-context.js new file mode 100644 index 000000000..139d85429 --- /dev/null +++ b/test/parallel/test-vm-new-script-new-context.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Script = require('vm').Script; + +common.globalCheck = false; + +console.error('run a string'); +var script = new Script('\'passed\';'); +console.error('script created'); +var result1 = script.runInNewContext(); +var result2 = script.runInNewContext(); +assert.equal('passed', result1); +assert.equal('passed', result2); + +console.error('thrown error'); +script = new Script('throw new Error(\'test\');'); +assert.throws(function() { + script.runInNewContext(); +}, /test/); + + + +console.error('undefined reference'); +var error; +script = new Script('foo.bar = 5;'); +assert.throws(function () { + script.runInNewContext(); +}, /not defined/); + + +hello = 5; +script = new Script('hello = 2'); +script.runInNewContext(); +assert.equal(5, hello); + + +console.error('pass values in and out'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (baz !== 3) throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +script = new Script(code); +var baz = script.runInNewContext(obj); +assert.equal(1, obj.foo); +assert.equal(2, obj.bar); +assert.equal(2, foo); + +console.error('call a function by reference'); +script = new Script('f()'); +function changeFoo() { foo = 100 } +script.runInNewContext({ f: changeFoo }); +assert.equal(foo, 100); + +console.error('modify an object by reference'); +script = new Script('f.a = 2'); +var f = { a: 1 }; +script.runInNewContext({ f: f }); +assert.equal(f.a, 2); + +assert.throws(function() { + script.runInNewContext(); +}, /f is not defined/); + +console.error('invalid this'); +assert.throws(function() { + script.runInNewContext.call('\'hello\';'); +}, TypeError); + + diff --git a/test/parallel/test-vm-new-script-this-context.js b/test/parallel/test-vm-new-script-this-context.js new file mode 100644 index 000000000..ff0b5b36f --- /dev/null +++ b/test/parallel/test-vm-new-script-this-context.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var Script = require('vm').Script; + +common.globalCheck = false; + +console.error('run a string'); +var script = new Script('\'passed\';'); +var result = script.runInThisContext(script); +assert.equal('passed', result); + +console.error('thrown error'); +script = new Script('throw new Error(\'test\');'); +assert.throws(function() { + script.runInThisContext(script); +}); + +hello = 5; +script = new Script('hello = 2'); +script.runInThisContext(script); +assert.equal(2, hello); + + +console.error('pass values'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +script = new Script(code); +script.runInThisContext(script); +assert.equal(0, obj.foo); +assert.equal(2, bar); +assert.equal(1, foo); + +console.error('call a function'); +f = function() { foo = 100 }; +script = new Script('f()'); +script.runInThisContext(script); +assert.equal(100, foo); diff --git a/test/parallel/test-vm-run-in-new-context.js b/test/parallel/test-vm-run-in-new-context.js new file mode 100644 index 000000000..ecb80bdbc --- /dev/null +++ b/test/parallel/test-vm-run-in-new-context.js @@ -0,0 +1,71 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Flags: --expose-gc + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +assert.equal(typeof gc, 'function', 'Run this test with --expose-gc'); + +common.globalCheck = false; + +console.error('run a string'); +var result = vm.runInNewContext('\'passed\';'); +assert.equal('passed', result); + +console.error('thrown error'); +assert.throws(function() { + vm.runInNewContext('throw new Error(\'test\');'); +}); + +hello = 5; +vm.runInNewContext('hello = 2'); +assert.equal(5, hello); + + +console.error('pass values in and out'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (baz !== 3) throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +var baz = vm.runInNewContext(code, obj); +assert.equal(1, obj.foo); +assert.equal(2, obj.bar); +assert.equal(2, foo); + +console.error('call a function by reference'); +function changeFoo() { foo = 100 } +vm.runInNewContext('f()', { f: changeFoo }); +assert.equal(foo, 100); + +console.error('modify an object by reference'); +var f = { a: 1 }; +vm.runInNewContext('f.a = 2', { f: f }); +assert.equal(f.a, 2); + +console.error('use function in context without referencing context'); +var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }) +gc(); +fn(); +// Should not crash diff --git a/test/parallel/test-vm-static-this.js b/test/parallel/test-vm-static-this.js new file mode 100644 index 000000000..860fbf04d --- /dev/null +++ b/test/parallel/test-vm-static-this.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +common.globalCheck = false; + +console.error('run a string'); +var result = vm.runInThisContext('\'passed\';'); +assert.equal('passed', result); + +console.error('thrown error'); +assert.throws(function() { + vm.runInThisContext('throw new Error(\'test\');'); +}, /test/); + +hello = 5; +vm.runInThisContext('hello = 2'); +assert.equal(2, hello); + + +console.error('pass values'); +code = 'foo = 1;' + + 'bar = 2;' + + 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; +foo = 2; +obj = { foo: 0, baz: 3 }; +var baz = vm.runInThisContext(code); +assert.equal(0, obj.foo); +assert.equal(2, bar); +assert.equal(1, foo); + +console.error('call a function'); +f = function() { foo = 100 }; +vm.runInThisContext('f()'); +assert.equal(100, foo); diff --git a/test/parallel/test-vm-timeout.js b/test/parallel/test-vm-timeout.js new file mode 100644 index 000000000..8ad2a234b --- /dev/null +++ b/test/parallel/test-vm-timeout.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var vm = require('vm'); + +// Test 1: Timeout of 100ms executing endless loop +assert.throws(function() { + vm.runInThisContext('while(true) {}', { timeout: 100 }); +}); + +// Test 2: Timeout must be >= 0ms +assert.throws(function() { + vm.runInThisContext('', { timeout: -1 }); +}, RangeError); + +// Test 3: Timeout of 0ms +assert.throws(function() { + vm.runInThisContext('', { timeout: 0 }); +}, RangeError); + +// Test 4: Timeout of 1000ms, script finishes first +vm.runInThisContext('', { timeout: 1000 }); + +// Test 5: Nested vm timeouts, inner timeout propagates out +assert.throws(function() { + var context = { + log: console.log, + runInVM: function(timeout) { + vm.runInNewContext('while(true) {}', context, { timeout: timeout }); + } + }; + vm.runInNewContext('runInVM(10)', context, { timeout: 100 }); + throw new Error('Test 5 failed'); +}, /Script execution timed out./); diff --git a/test/parallel/test-writedouble.js b/test/parallel/test-writedouble.js new file mode 100644 index 000000000..a700a82b4 --- /dev/null +++ b/test/parallel/test-writedouble.js @@ -0,0 +1,196 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're writing doubles correctly + */ +var common = require('../common'); +var ASSERT = require('assert'); + +function test(clazz) { + var buffer = new clazz(16); + + buffer.writeDoubleBE(2.225073858507201e-308, 0); + buffer.writeDoubleLE(2.225073858507201e-308, 8); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x0f, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0xff, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xff, buffer[7]); + ASSERT.equal(0xff, buffer[8]); + ASSERT.equal(0xff, buffer[9]); + ASSERT.equal(0xff, buffer[10]); + ASSERT.equal(0xff, buffer[11]); + ASSERT.equal(0xff, buffer[12]); + ASSERT.equal(0xff, buffer[13]); + ASSERT.equal(0x0f, buffer[14]); + ASSERT.equal(0x00, buffer[15]); + + buffer.writeDoubleBE(1.0000000000000004, 0); + buffer.writeDoubleLE(1.0000000000000004, 8); + ASSERT.equal(0x3f, buffer[0]); + ASSERT.equal(0xf0, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x02, buffer[7]); + ASSERT.equal(0x02, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0xf0, buffer[14]); + ASSERT.equal(0x3f, buffer[15]); + + buffer.writeDoubleBE(-2, 0); + buffer.writeDoubleLE(-2, 8); + ASSERT.equal(0xc0, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.equal(0x00, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0x00, buffer[14]); + ASSERT.equal(0xc0, buffer[15]); + + buffer.writeDoubleBE(1.7976931348623157e+308, 0); + buffer.writeDoubleLE(1.7976931348623157e+308, 8); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0xef, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0xff, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xff, buffer[7]); + ASSERT.equal(0xff, buffer[8]); + ASSERT.equal(0xff, buffer[9]); + ASSERT.equal(0xff, buffer[10]); + ASSERT.equal(0xff, buffer[11]); + ASSERT.equal(0xff, buffer[12]); + ASSERT.equal(0xff, buffer[13]); + ASSERT.equal(0xef, buffer[14]); + ASSERT.equal(0x7f, buffer[15]); + + buffer.writeDoubleBE(0 * -1, 0); + buffer.writeDoubleLE(0 * -1, 8); + ASSERT.equal(0x80, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.equal(0x00, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0x00, buffer[14]); + ASSERT.equal(0x80, buffer[15]); + + buffer.writeDoubleBE(Infinity, 0); + buffer.writeDoubleLE(Infinity, 8); + ASSERT.equal(0x7F, buffer[0]); + ASSERT.equal(0xF0, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.equal(0x00, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0xF0, buffer[14]); + ASSERT.equal(0x7F, buffer[15]); + ASSERT.equal(Infinity, buffer.readDoubleBE(0)); + ASSERT.equal(Infinity, buffer.readDoubleLE(8)); + + buffer.writeDoubleBE(-Infinity, 0); + buffer.writeDoubleLE(-Infinity, 8); + ASSERT.equal(0xFF, buffer[0]); + ASSERT.equal(0xF0, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.equal(0x00, buffer[8]); + ASSERT.equal(0x00, buffer[9]); + ASSERT.equal(0x00, buffer[10]); + ASSERT.equal(0x00, buffer[11]); + ASSERT.equal(0x00, buffer[12]); + ASSERT.equal(0x00, buffer[13]); + ASSERT.equal(0xF0, buffer[14]); + ASSERT.equal(0xFF, buffer[15]); + ASSERT.equal(-Infinity, buffer.readDoubleBE(0)); + ASSERT.equal(-Infinity, buffer.readDoubleLE(8)); + + buffer.writeDoubleBE(NaN, 0); + buffer.writeDoubleLE(NaN, 8); + // Darwin ia32 does the other kind of NaN. + // Compiler bug. No one really cares. + ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); + // mips processors use a slightly different NaN + ASSERT(0xF8 === buffer[1] || 0xF7 === buffer[1]); + ASSERT(0x00 === buffer[2] || 0xFF === buffer[2]); + ASSERT(0x00 === buffer[3] || 0xFF === buffer[3]); + ASSERT(0x00 === buffer[4] || 0xFF === buffer[4]); + ASSERT(0x00 === buffer[5] || 0xFF === buffer[5]); + ASSERT(0x00 === buffer[6] || 0xFF === buffer[6]); + ASSERT(0x00 === buffer[7] || 0xFF === buffer[7]); + ASSERT(0x00 === buffer[8] || 0xFF === buffer[8]); + ASSERT(0x00 === buffer[9] || 0xFF === buffer[9]); + ASSERT(0x00 === buffer[10] || 0xFF === buffer[10]); + ASSERT(0x00 === buffer[11] || 0xFF === buffer[11]); + ASSERT(0x00 === buffer[12] || 0xFF === buffer[12]); + ASSERT(0x00 === buffer[13] || 0xFF === buffer[13]); + ASSERT(0xF8 === buffer[14] || 0xF7 === buffer[14]); + // Darwin ia32 does the other kind of NaN. + // Compiler bug. No one really cares. + ASSERT(0x7F === buffer[15] || 0xFF === buffer[15]); + ASSERT.ok(isNaN(buffer.readDoubleBE(0))); + ASSERT.ok(isNaN(buffer.readDoubleLE(8))); +} + + +test(Buffer); diff --git a/test/parallel/test-writefloat.js b/test/parallel/test-writefloat.js new file mode 100644 index 000000000..0b4d21532 --- /dev/null +++ b/test/parallel/test-writefloat.js @@ -0,0 +1,134 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're writing floats correctly + */ +var common = require('../common'); +var ASSERT = require('assert'); + +function test(clazz) { + var buffer = new clazz(8); + + buffer.writeFloatBE(1, 0); + buffer.writeFloatLE(1, 4); + ASSERT.equal(0x3f, buffer[0]); + ASSERT.equal(0x80, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x80, buffer[6]); + ASSERT.equal(0x3f, buffer[7]); + + buffer.writeFloatBE(1 / 3, 0); + buffer.writeFloatLE(1 / 3, 4); + ASSERT.equal(0x3e, buffer[0]); + ASSERT.equal(0xaa, buffer[1]); + ASSERT.equal(0xaa, buffer[2]); + ASSERT.equal(0xab, buffer[3]); + ASSERT.equal(0xab, buffer[4]); + ASSERT.equal(0xaa, buffer[5]); + ASSERT.equal(0xaa, buffer[6]); + ASSERT.equal(0x3e, buffer[7]); + + buffer.writeFloatBE(3.4028234663852886e+38, 0); + buffer.writeFloatLE(3.4028234663852886e+38, 4); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0x7f, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0xff, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0x7f, buffer[6]); + ASSERT.equal(0x7f, buffer[7]); + + buffer.writeFloatLE(1.1754943508222875e-38, 0); + buffer.writeFloatBE(1.1754943508222875e-38, 4); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x80, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x80, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + + buffer.writeFloatBE(0 * -1, 0); + buffer.writeFloatLE(0 * -1, 4); + ASSERT.equal(0x80, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x80, buffer[7]); + + buffer.writeFloatBE(Infinity, 0); + buffer.writeFloatLE(Infinity, 4); + ASSERT.equal(0x7F, buffer[0]); + ASSERT.equal(0x80, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x80, buffer[6]); + ASSERT.equal(0x7F, buffer[7]); + ASSERT.equal(Infinity, buffer.readFloatBE(0)); + ASSERT.equal(Infinity, buffer.readFloatLE(4)); + + buffer.writeFloatBE(-Infinity, 0); + buffer.writeFloatLE(-Infinity, 4); + // Darwin ia32 does the other kind of NaN. + // Compiler bug. No one really cares. + ASSERT(0xFF === buffer[0] || 0x7F === buffer[0]); + ASSERT.equal(0x80, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x80, buffer[6]); + ASSERT.equal(0xFF, buffer[7]); + ASSERT.equal(-Infinity, buffer.readFloatBE(0)); + ASSERT.equal(-Infinity, buffer.readFloatLE(4)); + + buffer.writeFloatBE(NaN, 0); + buffer.writeFloatLE(NaN, 4); + // Darwin ia32 does the other kind of NaN. + // Compiler bug. No one really cares. + ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); + // mips processors use a slightly different NaN + ASSERT(0xC0 === buffer[1] || 0xBF === buffer[1]); + ASSERT(0x00 === buffer[2] || 0xFF === buffer[2]); + ASSERT(0x00 === buffer[3] || 0xFF === buffer[3]); + ASSERT(0x00 === buffer[4] || 0xFF === buffer[4]); + ASSERT(0x00 === buffer[5] || 0xFF === buffer[5]); + ASSERT(0xC0 === buffer[6] || 0xBF === buffer[6]); + // Darwin ia32 does the other kind of NaN. + // Compiler bug. No one really cares. + ASSERT(0x7F === buffer[7] || 0xFF === buffer[7]); + ASSERT.ok(isNaN(buffer.readFloatBE(0))); + ASSERT.ok(isNaN(buffer.readFloatLE(4))); +} + + +test(Buffer); diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js new file mode 100644 index 000000000..10540b6bd --- /dev/null +++ b/test/parallel/test-writeint.js @@ -0,0 +1,188 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * Tests to verify we're writing signed integers correctly + */ +var common = require('../common'); +var ASSERT = require('assert'); + +function test8(clazz) { + var buffer = new clazz(2); + + buffer.writeInt8(0x23, 0); + buffer.writeInt8(-5, 1); + + ASSERT.equal(0x23, buffer[0]); + ASSERT.equal(0xfb, buffer[1]); + + /* Make sure we handle truncation correctly */ + ASSERT.throws(function() { + buffer.writeInt8(0xabc, 0); + }); + ASSERT.throws(function() { + buffer.writeInt8(0xabc, 0); + }); + + /* Make sure we handle min/max correctly */ + buffer.writeInt8(0x7f, 0); + buffer.writeInt8(-0x80, 1); + + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0x80, buffer[1]); + ASSERT.throws(function() { + buffer.writeInt8(0x7f + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt8(-0x80 - 1, 0); + }); +} + + +function test16(clazz) { + var buffer = new clazz(6); + + buffer.writeInt16BE(0x0023, 0); + buffer.writeInt16LE(0x0023, 2); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x23, buffer[1]); + ASSERT.equal(0x23, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + + buffer.writeInt16BE(-5, 0); + buffer.writeInt16LE(-5, 2); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0xfb, buffer[1]); + ASSERT.equal(0xfb, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + + buffer.writeInt16BE(-1679, 1); + buffer.writeInt16LE(-1679, 3); + ASSERT.equal(0xf9, buffer[1]); + ASSERT.equal(0x71, buffer[2]); + ASSERT.equal(0x71, buffer[3]); + ASSERT.equal(0xf9, buffer[4]); + + /* Make sure we handle min/max correctly */ + buffer.writeInt16BE(0x7fff, 0); + buffer.writeInt16BE(-0x8000, 2); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0x80, buffer[2]); + ASSERT.equal(0x00, buffer[3]); + ASSERT.throws(function() { + buffer.writeInt16BE(0x7fff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt16BE(-0x8000 - 1, 0); + }); + + buffer.writeInt16LE(0x7fff, 0); + buffer.writeInt16LE(-0x8000, 2); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0x7f, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x80, buffer[3]); + ASSERT.throws(function() { + buffer.writeInt16LE(0x7fff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt16LE(-0x8000 - 1, 0); + }); +} + + +function test32(clazz) { + var buffer = new clazz(8); + + buffer.writeInt32BE(0x23, 0); + buffer.writeInt32LE(0x23, 4); + ASSERT.equal(0x00, buffer[0]); + ASSERT.equal(0x00, buffer[1]); + ASSERT.equal(0x00, buffer[2]); + ASSERT.equal(0x23, buffer[3]); + ASSERT.equal(0x23, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + + buffer.writeInt32BE(-5, 0); + buffer.writeInt32LE(-5, 4); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xfb, buffer[3]); + ASSERT.equal(0xfb, buffer[4]); + ASSERT.equal(0xff, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xff, buffer[7]); + + buffer.writeInt32BE(-805306713, 0); + buffer.writeInt32LE(-805306713, 4); + ASSERT.equal(0xcf, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xfe, buffer[2]); + ASSERT.equal(0xa7, buffer[3]); + ASSERT.equal(0xa7, buffer[4]); + ASSERT.equal(0xfe, buffer[5]); + ASSERT.equal(0xff, buffer[6]); + ASSERT.equal(0xcf, buffer[7]); + + /* Make sure we handle min/max correctly */ + buffer.writeInt32BE(0x7fffffff, 0); + buffer.writeInt32BE(-0x80000000, 4); + ASSERT.equal(0x7f, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0xff, buffer[3]); + ASSERT.equal(0x80, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x00, buffer[7]); + ASSERT.throws(function() { + buffer.writeInt32BE(0x7fffffff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt32BE(-0x80000000 - 1, 0); + }); + + buffer.writeInt32LE(0x7fffffff, 0); + buffer.writeInt32LE(-0x80000000, 4); + ASSERT.equal(0xff, buffer[0]); + ASSERT.equal(0xff, buffer[1]); + ASSERT.equal(0xff, buffer[2]); + ASSERT.equal(0x7f, buffer[3]); + ASSERT.equal(0x00, buffer[4]); + ASSERT.equal(0x00, buffer[5]); + ASSERT.equal(0x00, buffer[6]); + ASSERT.equal(0x80, buffer[7]); + ASSERT.throws(function() { + buffer.writeInt32LE(0x7fffffff + 1, 0); + }); + ASSERT.throws(function() { + buffer.writeInt32LE(-0x80000000 - 1, 0); + }); +} + + +test8(Buffer); +test16(Buffer); +test32(Buffer); diff --git a/test/parallel/test-writeuint.js b/test/parallel/test-writeuint.js new file mode 100644 index 000000000..da0d79528 --- /dev/null +++ b/test/parallel/test-writeuint.js @@ -0,0 +1,147 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* + * A battery of tests to help us read a series of uints + */ +var common = require('../common'); +var ASSERT = require('assert'); + +/* + * We need to check the following things: + * - We are correctly resolving big endian (doesn't mean anything for 8 bit) + * - Correctly resolving little endian (doesn't mean anything for 8 bit) + * - Correctly using the offsets + * - Correctly interpreting values that are beyond the signed range as unsigned + */ +function test8(clazz) { + var data = new clazz(4); + + data.writeUInt8(23, 0); + data.writeUInt8(23, 1); + data.writeUInt8(23, 2); + data.writeUInt8(23, 3); + ASSERT.equal(23, data[0]); + ASSERT.equal(23, data[1]); + ASSERT.equal(23, data[2]); + ASSERT.equal(23, data[3]); + + data.writeUInt8(23, 0); + data.writeUInt8(23, 1); + data.writeUInt8(23, 2); + data.writeUInt8(23, 3); + ASSERT.equal(23, data[0]); + ASSERT.equal(23, data[1]); + ASSERT.equal(23, data[2]); + ASSERT.equal(23, data[3]); + + data.writeUInt8(255, 0); + ASSERT.equal(255, data[0]); + + data.writeUInt8(255, 0); + ASSERT.equal(255, data[0]); +} + + +function test16(clazz) { + var value = 0x2343; + var data = new clazz(4); + + data.writeUInt16BE(value, 0); + ASSERT.equal(0x23, data[0]); + ASSERT.equal(0x43, data[1]); + + data.writeUInt16BE(value, 1); + ASSERT.equal(0x23, data[1]); + ASSERT.equal(0x43, data[2]); + + data.writeUInt16BE(value, 2); + ASSERT.equal(0x23, data[2]); + ASSERT.equal(0x43, data[3]); + + data.writeUInt16LE(value, 0); + ASSERT.equal(0x23, data[1]); + ASSERT.equal(0x43, data[0]); + + data.writeUInt16LE(value, 1); + ASSERT.equal(0x23, data[2]); + ASSERT.equal(0x43, data[1]); + + data.writeUInt16LE(value, 2); + ASSERT.equal(0x23, data[3]); + ASSERT.equal(0x43, data[2]); + + value = 0xff80; + data.writeUInt16LE(value, 0); + ASSERT.equal(0xff, data[1]); + ASSERT.equal(0x80, data[0]); + + data.writeUInt16BE(value, 0); + ASSERT.equal(0xff, data[0]); + ASSERT.equal(0x80, data[1]); +} + + +function test32(clazz) { + var data = new clazz(6); + var value = 0xe7f90a6d; + + data.writeUInt32BE(value, 0); + ASSERT.equal(0xe7, data[0]); + ASSERT.equal(0xf9, data[1]); + ASSERT.equal(0x0a, data[2]); + ASSERT.equal(0x6d, data[3]); + + data.writeUInt32BE(value, 1); + ASSERT.equal(0xe7, data[1]); + ASSERT.equal(0xf9, data[2]); + ASSERT.equal(0x0a, data[3]); + ASSERT.equal(0x6d, data[4]); + + data.writeUInt32BE(value, 2); + ASSERT.equal(0xe7, data[2]); + ASSERT.equal(0xf9, data[3]); + ASSERT.equal(0x0a, data[4]); + ASSERT.equal(0x6d, data[5]); + + data.writeUInt32LE(value, 0); + ASSERT.equal(0xe7, data[3]); + ASSERT.equal(0xf9, data[2]); + ASSERT.equal(0x0a, data[1]); + ASSERT.equal(0x6d, data[0]); + + data.writeUInt32LE(value, 1); + ASSERT.equal(0xe7, data[4]); + ASSERT.equal(0xf9, data[3]); + ASSERT.equal(0x0a, data[2]); + ASSERT.equal(0x6d, data[1]); + + data.writeUInt32LE(value, 2); + ASSERT.equal(0xe7, data[5]); + ASSERT.equal(0xf9, data[4]); + ASSERT.equal(0x0a, data[3]); + ASSERT.equal(0x6d, data[2]); +} + + +test8(Buffer); +test16(Buffer); +test32(Buffer); diff --git a/test/parallel/test-zlib-close-after-write.js b/test/parallel/test-zlib-close-after-write.js new file mode 100644 index 000000000..f0f176008 --- /dev/null +++ b/test/parallel/test-zlib-close-after-write.js @@ -0,0 +1,38 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +var closed = false; + +zlib.gzip('hello', function(err, out) { + var unzip = zlib.createGunzip(); + unzip.write(out); + unzip.close(function() { + closed = true; + }); +}); + +process.on('exit', function() { + assert(closed); +}); diff --git a/test/parallel/test-zlib-convenience-methods.js b/test/parallel/test-zlib-convenience-methods.js new file mode 100644 index 000000000..88cf82f04 --- /dev/null +++ b/test/parallel/test-zlib-convenience-methods.js @@ -0,0 +1,79 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test convenience methods with and without options supplied + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +var hadRun = 0; + +var expect = 'blahblahblahblahblahblah'; +var opts = { + level: 9, + chunkSize: 1024, +}; + +[ + ['gzip', 'gunzip'], + ['gzip', 'unzip'], + ['deflate', 'inflate'], + ['deflateRaw', 'inflateRaw'], +].forEach(function(method) { + + zlib[method[0]](expect, opts, function(err, result) { + zlib[method[1]](result, opts, function(err, result) { + assert.equal(result, expect, + 'Should get original string after ' + + method[0] + '/' + method[1] + ' with options.'); + hadRun++; + }); + }); + + zlib[method[0]](expect, function(err, result) { + zlib[method[1]](result, function(err, result) { + assert.equal(result, expect, + 'Should get original string after ' + + method[0] + '/' + method[1] + ' without options.'); + hadRun++; + }); + }); + + var result = zlib[method[0] + 'Sync'](expect, opts); + result = zlib[method[1] + 'Sync'](result, opts); + assert.equal(result, expect, + 'Should get original string after ' + + method[0] + '/' + method[1] + ' with options.'); + hadRun++; + + result = zlib[method[0] + 'Sync'](expect); + result = zlib[method[1] + 'Sync'](result); + assert.equal(result, expect, + 'Should get original string after ' + + method[0] + '/' + method[1] + ' without options.'); + hadRun++; + +}); + +process.on('exit', function() { + assert.equal(hadRun, 16, 'expect 16 compressions'); +}); diff --git a/test/parallel/test-zlib-dictionary-fail.js b/test/parallel/test-zlib-dictionary-fail.js new file mode 100644 index 000000000..fd35a0192 --- /dev/null +++ b/test/parallel/test-zlib-dictionary-fail.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +// Should raise an error, not trigger an assertion in src/node_zlib.cc +(function() { + var stream = zlib.createInflate(); + + stream.on('error', common.mustCall(function(err) { + assert(/Missing dictionary/.test(err.message)); + })); + + // String "test" encoded with dictionary "dict". + stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); +})(); + +// Should raise an error, not trigger an assertion in src/node_zlib.cc +(function() { + var stream = zlib.createInflate({ dictionary: Buffer('fail') }); + + stream.on('error', common.mustCall(function(err) { + assert(/Bad dictionary/.test(err.message)); + })); + + // String "test" encoded with dictionary "dict". + stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); +})(); diff --git a/test/parallel/test-zlib-dictionary.js b/test/parallel/test-zlib-dictionary.js new file mode 100644 index 000000000..58da810cc --- /dev/null +++ b/test/parallel/test-zlib-dictionary.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test compression/decompression with dictionary + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var spdyDict = new Buffer([ + 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-', + 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi', + 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser', + '-agent10010120020120220320420520630030130230330430530630740040140240340440', + '5406407408409410411412413414415416417500501502503504505accept-rangesageeta', + 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic', + 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran', + 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati', + 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo', + 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe', + 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic', + 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1', + '.1statusversionurl\0' +].join('')); + +var deflate = zlib.createDeflate({ dictionary: spdyDict }); + +var input = [ + 'HTTP/1.1 200 Ok', + 'Server: node.js', + 'Content-Length: 0', + '' +].join('\r\n'); + +var called = 0; + +// +// We'll use clean-new inflate stream each time +// and .reset() old dirty deflate one +// +function run(num) { + var inflate = zlib.createInflate({ dictionary: spdyDict }); + + if (num === 2) { + deflate.reset(); + deflate.removeAllListeners('data'); + } + + // Put data into deflate stream + deflate.on('data', function(chunk) { + inflate.write(chunk); + }); + + // Get data from inflate stream + var output = []; + inflate.on('data', function(chunk) { + output.push(chunk); + }); + inflate.on('end', function() { + called++; + + assert.equal(output.join(''), input); + + if (num < 2) run(num + 1); + }); + + deflate.write(input); + deflate.flush(function() { + inflate.end(); + }); +} +run(1); + +process.on('exit', function() { + assert.equal(called, 2); +}); diff --git a/test/parallel/test-zlib-flush.js b/test/parallel/test-zlib-flush.js new file mode 100644 index 000000000..0b189cecd --- /dev/null +++ b/test/parallel/test-zlib-flush.js @@ -0,0 +1,35 @@ +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); +var fs = require('fs'); + +var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')), + chunkSize = 16, + opts = { level: 0 }, + deflater = zlib.createDeflate(opts); + +var chunk = file.slice(0, chunkSize), + expectedNone = new Buffer([0x78, 0x01]), + blkhdr = new Buffer([0x00, 0x10, 0x00, 0xef, 0xff]), + adler32 = new Buffer([0x00, 0x00, 0x00, 0xff, 0xff]), + expectedFull = Buffer.concat([blkhdr, chunk, adler32]), + actualNone, + actualFull; + +deflater.write(chunk, function() { + deflater.flush(zlib.Z_NO_FLUSH, function() { + actualNone = deflater.read(); + deflater.flush(function() { + var bufs = [], buf; + while (buf = deflater.read()) + bufs.push(buf); + actualFull = Buffer.concat(bufs); + }); + }); +}); + +process.once('exit', function() { + assert.deepEqual(actualNone, expectedNone); + assert.deepEqual(actualFull, expectedFull); +}); diff --git a/test/parallel/test-zlib-from-gzip.js b/test/parallel/test-zlib-from-gzip.js new file mode 100644 index 000000000..399354209 --- /dev/null +++ b/test/parallel/test-zlib-from-gzip.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test unzipping a file that was created with a non-node gzip lib, +// piped in as fast as possible. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var gunzip = zlib.createGunzip(); + +var fs = require('fs'); + +var fixture = path.resolve(common.fixturesDir, 'person.jpg.gz'); +var unzippedFixture = path.resolve(common.fixturesDir, 'person.jpg'); +var outputFile = path.resolve(common.tmpDir, 'person.jpg'); +var expect = fs.readFileSync(unzippedFixture); +var inp = fs.createReadStream(fixture); +var out = fs.createWriteStream(outputFile); + +inp.pipe(gunzip).pipe(out); +out.on('close', function() { + var actual = fs.readFileSync(outputFile); + assert.equal(actual.length, expect.length, 'length should match'); + for (var i = 0, l = actual.length; i < l; i++) { + assert.equal(actual[i], expect[i], 'byte[' + i + ']'); + } +}); diff --git a/test/parallel/test-zlib-from-multiple-gzip-with-garbage.js b/test/parallel/test-zlib-from-multiple-gzip-with-garbage.js new file mode 100644 index 000000000..f6a0185e0 --- /dev/null +++ b/test/parallel/test-zlib-from-multiple-gzip-with-garbage.js @@ -0,0 +1,83 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test unzipping a file that was created by concatenating multiple gzip +// streams. + +var common = require('../common'); +var assert = require('assert'); +var zlib = require('zlib'); + +var util = require('util'); + +var gzipBuffer = new Buffer(128); +var gzipOffset = 0; + +var stream1 = '123\n'; +var stream2 = '456\n'; +var stream3 = '789\n'; + +function gzipAppend(data) { + data.copy(gzipBuffer, gzipOffset); + gzipOffset += data.length; +} + +function writeGzipStream(text, cb) { + var gzip = zlib.createGzip(); + gzip.on('data', gzipAppend); + gzip.write(text, function() { + gzip.flush(function() { + gzip.end(function() { + cb(); + }); + }); + }); +} + +function writeGarbageStream(text, cb) { + gzipAppend(new Buffer(text)); + cb(); +} + +writeGzipStream(stream1, function() { + writeGzipStream(stream2, function() { + writeGarbageStream(stream3, function() { + var gunzip = zlib.createGunzip(); + var gunzippedData = new Buffer(2 * 1024); + var gunzippedOffset = 0; + gunzip.on('data', function (data) { + data.copy(gunzippedData, gunzippedOffset); + gunzippedOffset += data.length; + }); + gunzip.on('error', function() { + assert.equal(gunzippedData.toString('utf8', 0, gunzippedOffset), + stream1 + stream2); + }); + gunzip.on('end', function() { + assert.fail('end event not expected'); + }); + + gunzip.write(gzipBuffer.slice(0, gzipOffset), 'binary', function() { + gunzip.end(); + }); + }); + }); +}); diff --git a/test/parallel/test-zlib-from-multiple-gzip.js b/test/parallel/test-zlib-from-multiple-gzip.js new file mode 100644 index 000000000..6f4127a4d --- /dev/null +++ b/test/parallel/test-zlib-from-multiple-gzip.js @@ -0,0 +1,74 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test unzipping a file that was created by concatenating multiple gzip +// streams. + +var common = require('../common'); +var assert = require('assert'); +var zlib = require('zlib'); + +var util = require('util'); + +var gzipBuffer = new Buffer(128); +var gzipOffset = 0; + +var stream1 = '123\n'; +var stream2 = '456\n'; +var stream3 = '789\n'; + +function gzipAppend(data) { + data.copy(gzipBuffer, gzipOffset); + gzipOffset += data.length; +} + +function writeGzipStream(text, cb) { + var gzip = zlib.createGzip(); + gzip.on('data', gzipAppend); + gzip.write(text, function() { + gzip.flush(function() { + gzip.end(function() { + cb(); + }); + }); + }); +} + +writeGzipStream(stream1, function() { + writeGzipStream(stream2, function() { + writeGzipStream(stream3, function() { + var gunzip = zlib.createGunzip(); + var gunzippedData = new Buffer(2 * 1024); + var gunzippedOffset = 0; + gunzip.on('data', function (data) { + data.copy(gunzippedData, gunzippedOffset); + gunzippedOffset += data.length; + }); + gunzip.on('end', function() { + assert.equal(gunzippedData.toString('utf8', 0, gunzippedOffset), stream1 + stream2 + stream3); + }); + + gunzip.write(gzipBuffer.slice(0, gzipOffset), 'binary', function() { + gunzip.end(); + }); + }); + }); +}); diff --git a/test/parallel/test-zlib-from-multiple-huge-gzip.js b/test/parallel/test-zlib-from-multiple-huge-gzip.js new file mode 100644 index 000000000..5533aafeb --- /dev/null +++ b/test/parallel/test-zlib-from-multiple-huge-gzip.js @@ -0,0 +1,93 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test unzipping a file that was created by concatenating multiple gzip +// streams. + +var common = require('../common'); +var assert = require('assert'); +var zlib = require('zlib'); + +var util = require('util'); + +var HUGE = 64 * 1024; + +var originalBuffer = new Buffer(3 * HUGE); +var originalOffset = 0; + +var gzipBuffer = new Buffer(3 * HUGE); +var gzipOffset = 0; + +function getRandomLetter() { + return (Math.random() * (122 - 97)) + 97; +} + +function generateHugeStream() { + var buffer = new Buffer(HUGE); + for (var i = 0; i < HUGE; i++) + buffer.writeUInt8(getRandomLetter(), i); + + buffer.copy(originalBuffer, originalOffset); + originalOffset += HUGE; + + return buffer; +} + +function gzipAppend(data) { + data.copy(gzipBuffer, gzipOffset); + gzipOffset += data.length; +} + +function writeGzipStream(text, cb) { + var gzip = zlib.createGzip(); + gzip.on('data', gzipAppend); + gzip.write(text, function() { + gzip.flush(function() { + gzip.end(function() { + cb(); + }); + }); + }); +} + +writeGzipStream(generateHugeStream(), function() { + writeGzipStream(generateHugeStream(), function() { + writeGzipStream(generateHugeStream(), function() { + var gunzip = zlib.createGunzip(); + var gunzippedData = new Buffer(3 * HUGE); + var gunzippedOffset = 0; + gunzip.on('data', function (data) { + data.copy(gunzippedData, gunzippedOffset); + gunzippedOffset += data.length; + }); + gunzip.on('end', function() { + var gunzippedStr = gunzippedData.toString('utf8', 0, gunzippedOffset); + var originalStr = originalBuffer.toString('utf8', 0, 3 * HUGE); + + assert.equal(gunzippedStr, originalStr); + }); + + gunzip.write(gzipBuffer.slice(0, gzipOffset), 'binary', function() { + gunzip.end(); + }); + }); + }); +}); diff --git a/test/parallel/test-zlib-from-string.js b/test/parallel/test-zlib-from-string.js new file mode 100644 index 000000000..83bdeea83 --- /dev/null +++ b/test/parallel/test-zlib-from-string.js @@ -0,0 +1,78 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test compressing and uncompressing a string with zlib + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +var inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el' + + 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' + + 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' + + ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' + + 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' + + 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' + + 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' + + 'cu malesuada fermentum. Nunc sed. '; +var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' + + 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' + + 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' + + 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' + + 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' + + 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9'; +var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' + + '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' + + 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' + + 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' + + 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' + + 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' + + 'HnHNzRtagj5AQAA'; + +zlib.deflate(inputString, function(err, buffer) { + assert.equal(buffer.toString('base64'), expectedBase64Deflate, + 'deflate encoded string should match'); +}); + +zlib.gzip(inputString, function(err, buffer) { + // Can't actually guarantee that we'll get exactly the same + // deflated bytes when we compress a string, since the header + // depends on stuff other than the input string itself. + // However, decrypting it should definitely yield the same + // result that we're expecting, and this should match what we get + // from inflating the known valid deflate data. + zlib.gunzip(buffer, function(err, gunzipped) { + assert.equal(gunzipped.toString(), inputString, + 'Should get original string after gzip/gunzip'); + }); +}); + +var buffer = new Buffer(expectedBase64Deflate, 'base64'); +zlib.unzip(buffer, function(err, buffer) { + assert.equal(buffer.toString(), inputString, + 'decoded inflated string should match'); +}); + +buffer = new Buffer(expectedBase64Gzip, 'base64'); +zlib.unzip(buffer, function(err, buffer) { + assert.equal(buffer.toString(), inputString, + 'decoded gunzipped string should match'); +}); diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js new file mode 100644 index 000000000..c3d8b5b47 --- /dev/null +++ b/test/parallel/test-zlib-invalid-input.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// test uncompressing invalid input + +var common = require('../common.js'), + assert = require('assert'), + zlib = require('zlib'); + +var nonStringInputs = [1, true, {a: 1}, ['a']]; + +console.error('Doing the non-strings'); +nonStringInputs.forEach(function(input) { + // zlib.gunzip should not throw an error when called with bad input. + assert.doesNotThrow(function() { + zlib.gunzip(input, function(err, buffer) { + // zlib.gunzip should pass the error to the callback. + assert.ok(err); + }); + }); +}); + +console.error('Doing the unzips'); +// zlib.Unzip classes need to get valid data, or else they'll throw. +var unzips = [ zlib.Unzip(), + zlib.Gunzip(), + zlib.Inflate(), + zlib.InflateRaw() ]; +var hadError = []; +unzips.forEach(function (uz, i) { + console.error('Error for '+uz.constructor.name); + uz.on('error', function(er) { + console.error('Error event', er); + hadError[i] = true; + }); + + uz.on('end', function(er) { + throw new Error('end event should not be emitted '+uz.constructor.name); + }); + + // this will trigger error event + uz.write('this is not valid compressed data.'); +}); + +process.on('exit', function() { + assert.deepEqual(hadError, [true, true, true, true], 'expect 4 errors'); +}); diff --git a/test/parallel/test-zlib-params.js b/test/parallel/test-zlib-params.js new file mode 100644 index 000000000..006f1ea8e --- /dev/null +++ b/test/parallel/test-zlib-params.js @@ -0,0 +1,33 @@ +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); +var fs = require('fs'); + +var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')), + chunkSize = 24 * 1024, + opts = { level: 9, strategy: zlib.Z_DEFAULT_STRATEGY }, + deflater = zlib.createDeflate(opts); + +var chunk1 = file.slice(0, chunkSize), + chunk2 = file.slice(chunkSize), + blkhdr = new Buffer([0x00, 0x48, 0x82, 0xb7, 0x7d]), + expected = Buffer.concat([blkhdr, chunk2]), + actual; + +deflater.write(chunk1, function() { + deflater.params(0, zlib.Z_DEFAULT_STRATEGY, function() { + while (deflater.read()); + deflater.end(chunk2, function() { + var bufs = [], buf; + while (buf = deflater.read()) + bufs.push(buf); + actual = Buffer.concat(bufs); + }); + }); + while (deflater.read()); +}); + +process.once('exit', function() { + assert.deepEqual(actual, expected); +}); diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js new file mode 100644 index 000000000..fc1db1cbb --- /dev/null +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -0,0 +1,181 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var crypto = require('crypto'); +var stream = require('stream'); +var Stream = stream.Stream; +var util = require('util'); +var assert = require('assert'); +var zlib = require('zlib'); + + + +// emit random bytes, and keep a shasum +function RandomReadStream(opt) { + Stream.call(this); + + this.readable = true; + this._paused = false; + this._processing = false; + + this._hasher = crypto.createHash('sha1'); + opt = opt || {}; + + // base block size. + opt.block = opt.block || 256 * 1024; + + // total number of bytes to emit + opt.total = opt.total || 256 * 1024 * 1024; + this._remaining = opt.total; + + // how variable to make the block sizes + opt.jitter = opt.jitter || 1024; + + this._opt = opt; + + this._process = this._process.bind(this); + + process.nextTick(this._process); +} + +util.inherits(RandomReadStream, Stream); + +RandomReadStream.prototype.pause = function() { + this._paused = true; + this.emit('pause'); +}; + +RandomReadStream.prototype.resume = function() { + // console.error("rrs resume"); + this._paused = false; + this.emit('resume'); + this._process(); +}; + +RandomReadStream.prototype._process = function() { + if (this._processing) return; + if (this._paused) return; + + this._processing = true; + + if (!this._remaining) { + this._hash = this._hasher.digest('hex').toLowerCase().trim(); + this._processing = false; + + this.emit('end'); + return; + } + + // figure out how many bytes to output + // if finished, then just emit end. + var block = this._opt.block; + var jitter = this._opt.jitter; + if (jitter) { + block += Math.ceil(Math.random() * jitter - (jitter / 2)); + } + block = Math.min(block, this._remaining); + var buf = new Buffer(block); + for (var i = 0; i < block; i++) { + buf[i] = Math.random() * 256; + } + + this._hasher.update(buf); + + this._remaining -= block; + + console.error('block=%d\nremain=%d\n', block, this._remaining); + this._processing = false; + + this.emit('data', buf); + process.nextTick(this._process); +}; + + +// a filter that just verifies a shasum +function HashStream() { + Stream.call(this); + + this.readable = this.writable = true; + this._hasher = crypto.createHash('sha1'); +} + +util.inherits(HashStream, Stream); + +HashStream.prototype.write = function(c) { + // Simulate the way that an fs.ReadStream returns false + // on *every* write like a jerk, only to resume a + // moment later. + this._hasher.update(c); + process.nextTick(this.resume.bind(this)); + return false; +}; + +HashStream.prototype.resume = function() { + this.emit('resume'); + process.nextTick(this.emit.bind(this, 'drain')); +}; + +HashStream.prototype.end = function(c) { + if (c) { + this.write(c); + } + this._hash = this._hasher.digest('hex').toLowerCase().trim(); + this.emit('data', this._hash); + this.emit('end'); +}; + + + + +var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); +var out = new HashStream(); +var gzip = zlib.createGzip(); +var gunz = zlib.createGunzip(); + +inp.pipe(gzip).pipe(gunz).pipe(out); + +inp.on('data', function(c) { + console.error('inp data', c.length); +}); + +gzip.on('data', function(c) { + console.error('gzip data', c.length); +}); + +gunz.on('data', function(c) { + console.error('gunz data', c.length); +}); + +out.on('data', function(c) { + console.error('out data', c.length); +}); + +var didSomething = false; +out.on('data', function(c) { + didSomething = true; + console.error('hash=%s', c); + assert.equal(c, inp._hash, 'hashes should match'); +}); + +process.on('exit', function() { + assert(didSomething, 'should have done something'); +}); diff --git a/test/parallel/test-zlib-write-after-close.js b/test/parallel/test-zlib-write-after-close.js new file mode 100644 index 000000000..d3f3d4e6b --- /dev/null +++ b/test/parallel/test-zlib-write-after-close.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); + +var closed = false; + +zlib.gzip('hello', function(err, out) { + var unzip = zlib.createGunzip(); + unzip.close(function() { + closed = true; + }); + assert.throws(function() { + unzip.write(out); + }); +}); + +process.on('exit', function() { + assert(closed); +}); diff --git a/test/parallel/test-zlib-write-after-flush.js b/test/parallel/test-zlib-write-after-flush.js new file mode 100644 index 000000000..e13871ecb --- /dev/null +++ b/test/parallel/test-zlib-write-after-flush.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var zlib = require('zlib'); +var fs = require('fs'); + +var gzip = zlib.createGzip(); +var gunz = zlib.createUnzip(); + +gzip.pipe(gunz); + +var output = ''; +var input = 'A line of data\n'; +gunz.setEncoding('utf8'); +gunz.on('data', function(c) { + output += c; +}); + +process.on('exit', function() { + assert.equal(output, input); + + // Make sure that the flush flag was set back to normal + assert.equal(gzip._flushFlag, zlib.Z_NO_FLUSH); + + console.log('ok'); +}); + +// make sure that flush/write doesn't trigger an assert failure +gzip.flush(); write(); +function write() { + gzip.write(input); + gzip.end(); + gunz.read(0); +} diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js new file mode 100644 index 000000000..31ac86bd6 --- /dev/null +++ b/test/parallel/test-zlib-zero-byte.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var zlib = require('zlib'); +var gz = zlib.Gzip() +var emptyBuffer = new Buffer(0); +var received = 0; +gz.on('data', function(c) { + received += c.length; +}); +var ended = false; +gz.on('end', function() { + ended = true; +}); +var finished = false; +gz.on('finish', function() { + finished = true; +}); +gz.write(emptyBuffer); +gz.end(); + +process.on('exit', function() { + assert.equal(received, 20); + assert(ended); + assert(finished); + console.log('ok'); +}); diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js new file mode 100644 index 000000000..b9267525e --- /dev/null +++ b/test/parallel/test-zlib.js @@ -0,0 +1,229 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var zlib = require('zlib'); +var path = require('path'); + +var zlibPairs = + [[zlib.Deflate, zlib.Inflate], + [zlib.Gzip, zlib.Gunzip], + [zlib.Deflate, zlib.Unzip], + [zlib.Gzip, zlib.Unzip], + [zlib.DeflateRaw, zlib.InflateRaw]]; + +// how fast to trickle through the slowstream +var trickle = [128, 1024, 1024 * 1024]; + +// tunable options for zlib classes. + +// several different chunk sizes +var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; + +// this is every possible value. +var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; +var windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; +var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; +var strategy = [0, 1, 2, 3, 4]; + +// it's nice in theory to test every combination, but it +// takes WAY too long. Maybe a pummel test could do this? +if (!process.env.PUMMEL) { + trickle = [1024]; + chunkSize = [1024 * 16]; + level = [6]; + memLevel = [8]; + windowBits = [15]; + strategy = [0]; +} + +var fs = require('fs'); + +var testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; + +if (process.env.FAST) { + zlibPairs = [[zlib.Gzip, zlib.Unzip]]; + var testFiles = ['person.jpg']; +} + +var tests = {}; +testFiles.forEach(function(file) { + tests[file] = fs.readFileSync(path.resolve(common.fixturesDir, file)); +}); + +var util = require('util'); +var stream = require('stream'); + + +// stream that saves everything +function BufferStream() { + this.chunks = []; + this.length = 0; + this.writable = true; + this.readable = true; +} + +util.inherits(BufferStream, stream.Stream); + +BufferStream.prototype.write = function(c) { + this.chunks.push(c); + this.length += c.length; + return true; +}; + +BufferStream.prototype.end = function(c) { + if (c) this.write(c); + // flatten + var buf = new Buffer(this.length); + var i = 0; + this.chunks.forEach(function(c) { + c.copy(buf, i); + i += c.length; + }); + this.emit('data', buf); + this.emit('end'); + return true; +}; + + +function SlowStream(trickle) { + this.trickle = trickle; + this.offset = 0; + this.readable = this.writable = true; +} + +util.inherits(SlowStream, stream.Stream); + +SlowStream.prototype.write = function() { + throw new Error('not implemented, just call ss.end(chunk)'); +}; + +SlowStream.prototype.pause = function() { + this.paused = true; + this.emit('pause'); +}; + +SlowStream.prototype.resume = function() { + var self = this; + if (self.ended) return; + self.emit('resume'); + if (!self.chunk) return; + self.paused = false; + emit(); + function emit() { + if (self.paused) return; + if (self.offset >= self.length) { + self.ended = true; + return self.emit('end'); + } + var end = Math.min(self.offset + self.trickle, self.length); + var c = self.chunk.slice(self.offset, end); + self.offset += c.length; + self.emit('data', c); + process.nextTick(emit); + } +}; + +SlowStream.prototype.end = function(chunk) { + // walk over the chunk in blocks. + var self = this; + self.chunk = chunk; + self.length = chunk.length; + self.resume(); + return self.ended; +}; + + + +// for each of the files, make sure that compressing and +// decompressing results in the same data, for every combination +// of the options set above. +var failures = 0; +var total = 0; +var done = 0; + +Object.keys(tests).forEach(function(file) { + var test = tests[file]; + chunkSize.forEach(function(chunkSize) { + trickle.forEach(function(trickle) { + windowBits.forEach(function(windowBits) { + level.forEach(function(level) { + memLevel.forEach(function(memLevel) { + strategy.forEach(function(strategy) { + zlibPairs.forEach(function(pair) { + var Def = pair[0]; + var Inf = pair[1]; + var opts = { level: level, + windowBits: windowBits, + memLevel: memLevel, + strategy: strategy }; + + total++; + + var def = new Def(opts); + var inf = new Inf(opts); + var ss = new SlowStream(trickle); + var buf = new BufferStream(); + + // verify that the same exact buffer comes out the other end. + buf.on('data', function(c) { + var msg = file + ' ' + + chunkSize + ' ' + + JSON.stringify(opts) + ' ' + + Def.name + ' -> ' + Inf.name; + var ok = true; + var testNum = ++done; + for (var i = 0; i < Math.max(c.length, test.length); i++) { + if (c[i] !== test[i]) { + ok = false; + failures++; + break; + } + } + if (ok) { + console.log('ok ' + (testNum) + ' ' + msg); + } else { + console.log('not ok ' + (testNum) + ' ' + msg); + console.log(' ...'); + console.log(' testfile: ' + file); + console.log(' type: ' + Def.name + ' -> ' + Inf.name); + console.log(' position: ' + i); + console.log(' options: ' + JSON.stringify(opts)); + console.log(' expect: ' + test[i]); + console.log(' actual: ' + c[i]); + console.log(' chunkSize: ' + chunkSize); + console.log(' ---'); + } + }); + + // the magic happens here. + ss.pipe(def).pipe(inf).pipe(buf); + ss.end(test); + }); + }); }); }); }); }); }); // sad stallman is sad. +}); + +process.on('exit', function(code) { + console.log('1..' + done); + assert.equal(done, total, (total - done) + ' tests left unfinished'); + assert.ok(!failures, 'some test failures'); +}); diff --git a/test/parallel/testcfg.py b/test/parallel/testcfg.py new file mode 100644 index 000000000..8b610b50b --- /dev/null +++ b/test/parallel/testcfg.py @@ -0,0 +1,6 @@ +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import testpy + +def GetConfiguration(context, root): + return testpy.ParallelTestConfiguration(context, root, 'parallel') diff --git a/test/sequential/test-chdir.js b/test/sequential/test-chdir.js new file mode 100644 index 000000000..7454bee2d --- /dev/null +++ b/test/sequential/test-chdir.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); + +assert.equal(true, process.cwd() !== __dirname); + +process.chdir(__dirname); +assert.equal(true, process.cwd() === __dirname); + +var dir = path.resolve(common.fixturesDir, + 'weird \uc3a4\uc3ab\uc3af characters \u00e1\u00e2\u00e3'); +fs.mkdirSync(dir); +process.chdir(dir); +assert(process.cwd() == dir); + +process.chdir('..'); +assert(process.cwd() == path.resolve(common.fixturesDir)); +fs.rmdirSync(dir); diff --git a/test/sequential/test-child-process-emfile.js b/test/sequential/test-child-process-emfile.js new file mode 100644 index 000000000..323bbb0a3 --- /dev/null +++ b/test/sequential/test-child-process-emfile.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var fs = require('fs'); + +if (process.platform === 'win32') { + console.log('Skipping test, no RLIMIT_NOFILE on Windows.'); + return; +} + +for (;;) { + try { + fs.openSync(__filename, 'r'); + } catch (err) { + assert(err.code === 'EMFILE' || err.code === 'ENFILE'); + break; + } +} + +// Should emit an error, not throw. +var proc = spawn(process.execPath, ['-e', '0']); + +proc.on('error', common.mustCall(function(err) { + assert(err.code === 'EMFILE' || err.code === 'ENFILE'); +})); + +// 'exit' should not be emitted, the process was never spawned. +proc.on('exit', assert.fail); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js new file mode 100644 index 000000000..e97de721f --- /dev/null +++ b/test/sequential/test-child-process-execsync.js @@ -0,0 +1,105 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var util = require('util'); +var os = require('os'); + +var execSync = require('child_process').execSync; +var execFileSync = require('child_process').execFileSync; + +var TIMER = 200; +var SLEEP = 2000; + +var start = Date.now(); +var err; +var caught = false; +try +{ + var cmd = util.format('%s -e "setTimeout(function(){}, %d);"', + process.execPath, SLEEP); + var ret = execSync(cmd, {timeout: TIMER}); +} catch (e) { + caught = true; + assert.strictEqual(e.errno, 'ETIMEDOUT'); + err = e; +} finally { + assert.strictEqual(ret, undefined, 'we should not have a return value'); + assert.strictEqual(caught, true, 'execSync should throw'); + var end = Date.now() - start; + assert(end < SLEEP); + assert(err.status > 128 || err.signal); +} + +assert.throws(function() { + execSync('iamabadcommand'); +}, /Command failed: iamabadcommand/); + +var msg = 'foobar'; +var msgBuf = new Buffer(msg + '\n'); + +// console.log ends every line with just '\n', even on Windows. +cmd = util.format('%s -e "console.log(\'%s\');"', process.execPath, msg); + +var ret = execSync(cmd); + +assert.strictEqual(ret.length, msgBuf.length); +assert.deepEqual(ret, msgBuf, 'execSync result buffer should match'); + +ret = execSync(cmd, { encoding: 'utf8' }); + +assert.strictEqual(ret, msg + '\n', 'execSync encoding result should match'); + +var args = [ + '-e', + util.format('console.log("%s");', msg) +]; +ret = execFileSync(process.execPath, args); + +assert.deepEqual(ret, msgBuf); + +ret = execFileSync(process.execPath, args, { encoding: 'utf8' }); + +assert.strictEqual(ret, msg + '\n', 'execFileSync encoding result should match'); + +// Verify that the cwd option works - GH #7824 +(function() { + var response; + var cwd; + + if (process.platform === 'win32') { + cwd = 'c:\\'; + response = execSync('echo %cd%', {cwd: cwd}); + } else { + cwd = '/'; + response = execSync('pwd', {cwd: cwd}); + } + + assert.strictEqual(response.toString().trim(), cwd); +})(); + +// Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 +(function() { + assert.throws(function() { + execSync('exit -1', {stdio: 'ignore'}); + }, /Command failed: exit -1/); +})(); diff --git a/test/sequential/test-child-process-fork-getconnections.js b/test/sequential/test-child-process-fork-getconnections.js new file mode 100644 index 000000000..f8fed6884 --- /dev/null +++ b/test/sequential/test-child-process-fork-getconnections.js @@ -0,0 +1,119 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var common = require('../common'); +var fork = require('child_process').fork; +var net = require('net'); +var count = 12; + +if (process.argv[2] === 'child') { + var sockets = []; + var id = process.argv[3]; + + process.on('message', function(m, socket) { + if (m.cmd === 'new') { + assert(socket); + assert(socket instanceof net.Socket, 'should be a net.Socket'); + sockets.push(socket); + socket.on('end', function() { + if (!this.closingOnPurpose) + throw new Error('[c] closing by accident!'); + }); + } + + if (m.cmd === 'close') { + assert.equal(socket, undefined); + sockets[m.id].once('close', function() { + process.send({ id: m.id, status: 'closed' }); + }); + sockets[m.id].destroy(); + } + }); + +} else { + var child = fork(process.argv[1], ['child']); + + child.on('exit', function(code, signal) { + if (!childKilled) + throw new Error('child died unexpectedly!'); + }); + + var server = net.createServer(); + var sockets = []; + var sent = 0; + + server.on('connection', function(socket) { + child.send({ cmd: 'new' }, socket, { track: false }); + sockets.push(socket); + + if (sockets.length === count) { + closeSockets(0); + } + }); + + var disconnected = 0; + var clients = []; + server.on('listening', function() { + var j = count, client; + while (j--) { + client = net.connect(common.PORT, '127.0.0.1'); + client.id = j; + client.on('close', function() { + disconnected += 1; + }); + clients.push(client); + } + }); + + var childKilled = false; + function closeSockets(i) { + if (i === count) { + childKilled = true; + server.close(); + child.kill(); + return; + } + + sent++; + child.send({ id: i, cmd: 'close' }); + child.once('message', function(m) { + assert(m.status === 'closed'); + server.getConnections(function(err, num) { + closeSockets(i + 1); + }); + }); + }; + + var closeEmitted = false; + server.on('close', function() { + closeEmitted = true; + }); + + server.listen(common.PORT, '127.0.0.1'); + + process.on('exit', function() { + assert.equal(sent, count); + assert.equal(disconnected, count); + assert.ok(closeEmitted); + console.log('ok'); + }); +} diff --git a/test/sequential/test-cluster-listening-port.js b/test/sequential/test-cluster-listening-port.js new file mode 100644 index 000000000..352c4d757 --- /dev/null +++ b/test/sequential/test-cluster-listening-port.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +if (cluster.isMaster) { + var port = null; + cluster.fork(); + cluster.on('listening', function(worker, address) { + port = address.port; + // ensure that the port is not 0 or null + assert(port); + // ensure that the port is numerical + assert.strictEqual(typeof(port), 'number'); + worker.kill(); + }); + process.on('exit', function() { + // ensure that the 'listening' handler has been called + assert(port); + }); +} +else { + net.createServer(assert.fail).listen(0); +} diff --git a/test/sequential/test-debug-args.js b/test/sequential/test-debug-args.js new file mode 100644 index 000000000..51eaa801d --- /dev/null +++ b/test/sequential/test-debug-args.js @@ -0,0 +1,27 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Flags: --debugger + +var common = require('../common'); +var assert = require('assert'); + +assert.notEqual(process.execArgv.indexOf('--debugger'), -1); diff --git a/test/sequential/test-debug-cluster.js b/test/sequential/test-debug-cluster.js new file mode 100644 index 000000000..c0963c35a --- /dev/null +++ b/test/sequential/test-debug-cluster.js @@ -0,0 +1,63 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var args = ['--debug', common.fixturesDir + '/clustered-server/app.js' ]; +var child = spawn(process.execPath, args); +var outputLines = []; + +child.stderr.on('data', function(data) { + var lines = data.toString().replace(/\r/g, '').trim().split('\n'); + var line = lines[0]; + + lines.forEach(function(ln) { console.log('> ' + ln) } ); + + if (line === 'all workers are running') { + assertOutputLines(); + process.exit(); + } else { + outputLines = outputLines.concat(lines); + } +}); + +process.on('exit', function onExit() { + child.kill(); +}); + +var assertOutputLines = common.mustCall(function() { + var expectedLines = [ + 'Debugger listening on port ' + 5858, + 'Debugger listening on port ' + 5859, + 'Debugger listening on port ' + 5860, + ]; + + // Do not assume any particular order of output messages, + // since workers can take different amout of time to + // start up + outputLines.sort(); + + assert.equal(outputLines.length, expectedLines.length) + for (var i = 0; i < expectedLines.length; i++) + assert.equal(outputLines[i], expectedLines[i]); +}); diff --git a/test/sequential/test-debug-port-cluster.js b/test/sequential/test-debug-port-cluster.js new file mode 100644 index 000000000..34ae3a029 --- /dev/null +++ b/test/sequential/test-debug-port-cluster.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var port = common.PORT + 1337; + +var args = [ + '--debug=' + port, + common.fixturesDir + '/clustered-server/app.js' +]; + +var child = spawn(process.execPath, args); +var outputLines = []; + +child.stderr.on('data', function(data) { + var lines = data.toString().replace(/\r/g, '').trim().split('\n'); + var line = lines[0]; + + lines.forEach(function(ln) { console.log('> ' + ln) } ); + + if (line === 'all workers are running') { + assertOutputLines(); + process.exit(); + } else { + outputLines = outputLines.concat(lines); + } +}); + +process.on('exit', function onExit() { + child.kill(); +}); + +var assertOutputLines = common.mustCall(function() { + var expectedLines = [ + 'Debugger listening on port ' + port, + 'Debugger listening on port ' + (port+1), + 'Debugger listening on port ' + (port+2), + ]; + + // Do not assume any particular order of output messages, + // since workers can take different amout of time to + // start up + outputLines.sort(); + + assert.equal(outputLines.length, expectedLines.length) + for (var i = 0; i < expectedLines.length; i++) + assert.equal(outputLines[i], expectedLines[i]); +}); diff --git a/test/sequential/test-debug-port-from-cmdline.js b/test/sequential/test-debug-port-from-cmdline.js new file mode 100644 index 000000000..db0f1b382 --- /dev/null +++ b/test/sequential/test-debug-port-from-cmdline.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var debugPort = common.PORT; +var args = ['--debug-port=' + debugPort]; +var child = spawn(process.execPath, args); + +child.stderr.on('data', function(data) { + var lines = data.toString().replace(/\r/g, '').trim().split('\n'); + lines.forEach(processStderrLine); +}); + +setTimeout(testTimedOut, 3000); +function testTimedOut() { + assert(false, 'test timed out.'); +} + +// Give the child process small amout of time to start +setTimeout(function() { + process._debugProcess(child.pid); +}, 100); + +process.on('exit', function() { + child.kill(); +}); + +var outputLines = []; +function processStderrLine(line) { + console.log('> ' + line); + outputLines.push(line); + + if (/Debugger listening/.test(line)) { + assertOutputLines(); + process.exit(); + } +} + +function assertOutputLines() { + var expectedLines = [ + 'Starting debugger agent.', + 'Debugger listening on port ' + debugPort + ]; + + assert.equal(outputLines.length, expectedLines.length); + for (var i = 0; i < expectedLines.length; i++) + assert.equal(outputLines[i], expectedLines[i]); + +} diff --git a/test/sequential/test-debug-signal-cluster.js b/test/sequential/test-debug-signal-cluster.js new file mode 100644 index 000000000..cd57e548a --- /dev/null +++ b/test/sequential/test-debug-signal-cluster.js @@ -0,0 +1,102 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +var args = [ common.fixturesDir + '/clustered-server/app.js' ]; +var child = spawn(process.execPath, args, { + stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ] +}); +var outputLines = []; +var outputTimerId; +var waitingForDebuggers = false; + +var pids = null; + +child.stderr.on('data', function(data) { + var lines = data.toString().replace(/\r/g, '').trim().split('\n'); + var line = lines[0]; + + lines.forEach(function(ln) { console.log('> ' + ln) } ); + + if (outputTimerId !== undefined) + clearTimeout(outputTimerId); + + if (waitingForDebuggers) { + outputLines = outputLines.concat(lines); + outputTimerId = setTimeout(onNoMoreLines, 800); + } else if (line === 'all workers are running') { + child.on('message', function(msg) { + if (msg.type !== 'pids') + return; + + pids = msg.pids; + console.error('got pids %j', pids); + + waitingForDebuggers = true; + process._debugProcess(child.pid); + }); + + child.send({ + type: 'getpids' + }); + } +}); + +function onNoMoreLines() { + assertOutputLines(); + process.exit(); +} + +setTimeout(function testTimedOut() { + assert(false, 'test timed out.'); +}, 6000); + +process.on('exit', function onExit() { + // Kill processes in reverse order to avoid timing problems on Windows where + // the parent process is killed before the children. + pids.reverse().forEach(function(pid) { + process.kill(pid); + }); +}); + +function assertOutputLines() { + var expectedLines = [ + 'Starting debugger agent.', + 'Debugger listening on port ' + 5858, + 'Starting debugger agent.', + 'Debugger listening on port ' + 5859, + 'Starting debugger agent.', + 'Debugger listening on port ' + 5860, + ]; + + // Do not assume any particular order of output messages, + // since workers can take different amout of time to + // start up + outputLines.sort(); + expectedLines.sort(); + + assert.equal(outputLines.length, expectedLines.length); + for (var i = 0; i < expectedLines.length; i++) + assert.equal(outputLines[i], expectedLines[i]); +} diff --git a/test/sequential/test-deprecation-flags.js b/test/sequential/test-deprecation-flags.js new file mode 100644 index 000000000..3d50c097f --- /dev/null +++ b/test/sequential/test-deprecation-flags.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var execFile = require('child_process').execFile; +var depmod = require.resolve('../fixtures/deprecated.js'); +var node = process.execPath; + +var normal = [depmod]; +var noDep = ['--no-deprecation', depmod]; +var traceDep = ['--trace-deprecation', depmod]; + +execFile(node, normal, function(er, stdout, stderr) { + console.error('normal: show deprecation warning'); + assert.equal(er, null); + assert.equal(stdout, ''); + assert.equal(stderr, 'util.p: Use console.error() instead\n\'This is deprecated\'\n'); + console.log('normal ok'); +}); + +execFile(node, noDep, function(er, stdout, stderr) { + console.error('--no-deprecation: silence deprecations'); + assert.equal(er, null); + assert.equal(stdout, ''); + assert.equal(stderr, '\'This is deprecated\'\n'); + console.log('silent ok'); +}); + +execFile(node, traceDep, function(er, stdout, stderr) { + console.error('--trace-deprecation: show stack'); + assert.equal(er, null); + assert.equal(stdout, ''); + var stack = stderr.trim().split('\n'); + // just check the top and bottom. + assert.equal(stack[0], 'Trace: util.p: Use console.error() instead'); + assert.equal(stack.pop(), '\'This is deprecated\''); + console.log('trace ok'); +}); diff --git a/test/sequential/test-force-repl.js b/test/sequential/test-force-repl.js new file mode 100644 index 000000000..60ba3485b --- /dev/null +++ b/test/sequential/test-force-repl.js @@ -0,0 +1,44 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +// spawn a node child process in "interactive" mode (force the repl) +var cp = spawn(process.execPath, ['-i']); +var gotToEnd = false; +var timeoutId = setTimeout(function() { + throw new Error('timeout!'); +}, 1000); // give node + the repl 1 second to boot up + +cp.stdout.setEncoding('utf8'); + +cp.stdout.once('data', function(b) { + clearTimeout(timeoutId); + assert.equal(b, '> '); + gotToEnd = true; + cp.kill(); +}); + +process.on('exit', function() { + assert(gotToEnd); +}); diff --git a/test/sequential/test-fs-watch-recursive.js b/test/sequential/test-fs-watch-recursive.js new file mode 100644 index 000000000..e421ab022 --- /dev/null +++ b/test/sequential/test-fs-watch-recursive.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +if (process.platform === 'darwin') { + var watchSeenOne = 0; + + var testDir = common.tmpDir; + + var filenameOne = 'watch.txt'; + var testsubdirName = 'testsubdir'; + var testsubdir = path.join(testDir, testsubdirName); + var relativePathOne = path.join('testsubdir', filenameOne); + var filepathOne = path.join(testsubdir, filenameOne); + + process.on('exit', function() { + assert.ok(watchSeenOne > 0); + }); + + function cleanup() { + try { fs.unlinkSync(filepathOne); } catch (e) { } + try { fs.rmdirSync(testsubdir); } catch (e) { } + }; + + try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} + + assert.doesNotThrow(function() { + var watcher = fs.watch(testDir, {recursive: true}); + watcher.on('change', function(event, filename) { + assert.ok('change' === event || 'rename' === event); + + // Ignore stale events generated by mkdir + if (filename === testsubdirName) + return; + + assert.equal(relativePathOne, filename); + + watcher.close(); + cleanup(); + ++watchSeenOne; + }); + }); + + setTimeout(function() { + fs.writeFileSync(filepathOne, 'world'); + }, 10); +} diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js new file mode 100644 index 000000000..470736d59 --- /dev/null +++ b/test/sequential/test-fs-watch.js @@ -0,0 +1,152 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var expectFilePath = process.platform === 'win32' || + process.platform === 'linux' || + process.platform === 'darwin'; + +var watchSeenOne = 0; +var watchSeenTwo = 0; +var watchSeenThree = 0; + +var testDir = common.tmpDir; + +var filenameOne = 'watch.txt'; +var filepathOne = path.join(testDir, filenameOne); + +var filenameTwo = 'hasOwnProperty'; +var filepathTwo = filenameTwo; +var filepathTwoAbs = path.join(testDir, filenameTwo); + +var filenameThree = 'newfile.txt'; +var testsubdir = path.join(testDir, 'testsubdir'); +var filepathThree = path.join(testsubdir, filenameThree); + + +process.on('exit', function() { + assert.ok(watchSeenOne > 0); + assert.ok(watchSeenTwo > 0); + assert.ok(watchSeenThree > 0); +}); + +// Clean up stale files (if any) from previous run. +try { fs.unlinkSync(filepathOne); } catch (e) { } +try { fs.unlinkSync(filepathTwoAbs); } catch (e) { } +try { fs.unlinkSync(filepathThree); } catch (e) { } +try { fs.rmdirSync(testsubdir); } catch (e) { } + +fs.writeFileSync(filepathOne, 'hello'); + +assert.doesNotThrow( + function() { + var watcher = fs.watch(filepathOne) + watcher.on('change', function(event, filename) { + assert.equal('change', event); + + if (expectFilePath) { + assert.equal('watch.txt', filename); + } + watcher.close(); + ++watchSeenOne; + }); + } +); + +setTimeout(function() { + fs.writeFileSync(filepathOne, 'world'); +}, 10); + + +process.chdir(testDir); + +fs.writeFileSync(filepathTwoAbs, 'howdy'); + +assert.doesNotThrow( + function() { + var watcher = fs.watch(filepathTwo, function(event, filename) { + assert.equal('change', event); + + if (expectFilePath) { + assert.equal('hasOwnProperty', filename); + } + watcher.close(); + ++watchSeenTwo; + }); + } +); + +setTimeout(function() { + fs.writeFileSync(filepathTwoAbs, 'pardner'); +}, 10); + +try { fs.unlinkSync(filepathThree); } catch (e) {} +try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} + +assert.doesNotThrow( + function() { + var watcher = fs.watch(testsubdir, function(event, filename) { + var renameEv = process.platform === 'sunos' ? 'change' : 'rename'; + assert.equal(renameEv, event); + if (expectFilePath) { + assert.equal('newfile.txt', filename); + } else { + assert.equal(null, filename); + } + watcher.close(); + ++watchSeenThree; + }); + } +); + +setTimeout(function() { + var fd = fs.openSync(filepathThree, 'w'); + fs.closeSync(fd); +}, 10); + +// https://github.com/joyent/node/issues/2293 - non-persistent watcher should +// not block the event loop +fs.watch(__filename, {persistent: false}, function() { + assert(0); +}); + +// whitebox test to ensure that wrapped FSEvent is safe +// https://github.com/joyent/node/issues/6690 +var oldhandle; +assert.throws(function() { + var w = fs.watch(__filename, function(event, filename) { }); + oldhandle = w._handle; + w._handle = { close: w._handle.close }; + w.close(); +}, TypeError); +oldhandle.close(); // clean up + +assert.throws(function() { + var w = fs.watchFile(__filename, {persistent:false}, function(){}); + oldhandle = w._handle; + w._handle = { stop: w._handle.stop }; + w.stop(); +}, TypeError); +oldhandle.stop(); // clean up diff --git a/test/sequential/test-http-pipeline-flood.js b/test/sequential/test-http-pipeline-flood.js new file mode 100644 index 000000000..64c56dbf3 --- /dev/null +++ b/test/sequential/test-http-pipeline-flood.js @@ -0,0 +1,112 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +switch (process.argv[2]) { + case undefined: + return parent(); + case 'child': + return child(); + default: + throw new Error('wtf'); +} + +function parent() { + var http = require('http'); + var bigResponse = new Buffer(10240).fill('x'); + var gotTimeout = false; + var childClosed = false; + var requests = 0; + var connections = 0; + + var server = http.createServer(function(req, res) { + requests++; + res.setHeader('content-length', bigResponse.length); + res.end(bigResponse); + }); + + server.on('connection', function(conn) { + connections++; + }); + + // kill the connection after a bit, verifying that the + // flood of requests was eventually halted. + server.setTimeout(200, function(conn) { + gotTimeout = true; + conn.destroy(); + }); + + server.listen(common.PORT, function() { + var spawn = require('child_process').spawn; + var args = [__filename, 'child']; + var child = spawn(process.execPath, args, { stdio: 'inherit' }); + child.on('close', function(code) { + assert(!code); + childClosed = true; + server.close(); + }); + }); + + process.on('exit', function() { + assert(gotTimeout); + assert(childClosed); + assert.equal(connections, 1); + // The number of requests we end up processing before the outgoing + // connection backs up and requires a drain is implementation-dependent. + // We can safely assume is more than 250. + console.log('server got %d requests', requests); + assert(requests >= 250); + console.log('ok'); + }); +} + +function child() { + var net = require('net'); + + var gotEpipe = false; + var conn = net.connect({ port: common.PORT }); + + var req = 'GET / HTTP/1.1\r\nHost: localhost:' + + common.PORT + '\r\nAccept: */*\r\n\r\n'; + + req = new Array(10241).join(req); + + conn.on('connect', function() { + write(); + }); + + conn.on('drain', write); + + conn.on('error', function(er) { + gotEpipe = true; + }); + + process.on('exit', function() { + assert(gotEpipe); + console.log('ok - child'); + }); + + function write() { + while (false !== conn.write(req, 'ascii')); + } +} diff --git a/test/sequential/test-init.js b/test/sequential/test-init.js new file mode 100644 index 000000000..139df7f58 --- /dev/null +++ b/test/sequential/test-init.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +(function() { + var assert = require('assert'), + child = require('child_process'), + util = require('util'), + common = require('../common'); + if (process.env['TEST_INIT']) { + util.print('Loaded successfully!'); + } else { + // change CWD as we do this test so its not dependant on current CWD + // being in the test folder + process.chdir(__dirname); + + // slow but simple + var envCopy = JSON.parse(JSON.stringify(process.env)); + envCopy.TEST_INIT = 1; + + child.exec(process.execPath + ' test-init', {env: envCopy}, + function(err, stdout, stderr) { + assert.equal(stdout, 'Loaded successfully!', + '`node test-init` failed!'); + }); + child.exec(process.execPath + ' test-init.js', {env: envCopy}, + function(err, stdout, stderr) { + assert.equal(stdout, 'Loaded successfully!', + '`node test-init.js` failed!'); + }); + + // test-init-index is in fixtures dir as requested by ry, so go there + process.chdir(common.fixturesDir); + + child.exec(process.execPath + ' test-init-index', {env: envCopy}, + function(err, stdout, stderr) { + assert.equal(stdout, 'Loaded successfully!', + '`node test-init-index failed!'); + }); + + // ensures that `node fs` does not mistakenly load the native 'fs' module + // instead of the desired file and that the fs module loads as + // expected in node + process.chdir(common.fixturesDir + '/test-init-native/'); + + child.exec(process.execPath + ' fs', {env: envCopy}, + function(err, stdout, stderr) { + assert.equal(stdout, 'fs loaded successfully', + '`node fs` failed!'); + }); + } +})(); diff --git a/test/sequential/test-memory-usage-emfile.js b/test/sequential/test-memory-usage-emfile.js new file mode 100644 index 000000000..aaed89953 --- /dev/null +++ b/test/sequential/test-memory-usage-emfile.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var fs = require('fs'); + +var files = []; + +while (files.length < 256) + files.push(fs.openSync(__filename, 'r')); + +var r = process.memoryUsage(); +console.log(common.inspect(r)); +assert.equal(true, r['rss'] > 0); diff --git a/test/sequential/test-mkdir-rmdir.js b/test/sequential/test-mkdir-rmdir.js new file mode 100644 index 000000000..73534555c --- /dev/null +++ b/test/sequential/test-mkdir-rmdir.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var dirname = path.dirname(__filename); +var d = path.join(common.tmpDir, 'dir'); + +var mkdir_error = false; +var rmdir_error = false; + +fs.mkdir(d, 0666, function(err) { + if (err) { + console.log('mkdir error: ' + err.message); + mkdir_error = true; + } else { + fs.mkdir(d, 0666, function(err) { + console.log('expect EEXIST error: ', err); + assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); + assert.equal(err.code, 'EEXIST', 'got EEXIST code'); + assert.equal(err.path, d, 'got proper path for EEXIST'); + + console.log('mkdir okay!'); + fs.rmdir(d, function(err) { + if (err) { + console.log('rmdir error: ' + err.message); + rmdir_error = true; + } else { + console.log('rmdir okay!'); + } + }); + }); + } +}); + +process.on('exit', function() { + assert.equal(false, mkdir_error); + assert.equal(false, rmdir_error); + console.log('exit'); +}); diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js new file mode 100644 index 000000000..c923d56fd --- /dev/null +++ b/test/sequential/test-module-loading.js @@ -0,0 +1,308 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +common.debug('load test-module-loading.js'); + +// assert that this is the main module. +assert.equal(require.main.id, '.', 'main module should have id of \'.\''); +assert.equal(require.main, module, 'require.main should === module'); +assert.equal(process.mainModule, module, + 'process.mainModule should === module'); +// assert that it's *not* the main module in the required module. +require('../fixtures/not-main-module.js'); + +// require a file with a request that includes the extension +var a_js = require('../fixtures/a.js'); +assert.equal(42, a_js.number); + +// require a file without any extensions +var foo_no_ext = require('../fixtures/foo'); +assert.equal('ok', foo_no_ext.foo); + +var a = require('../fixtures/a'); +var c = require('../fixtures/b/c'); +var d = require('../fixtures/b/d'); +var d2 = require('../fixtures/b/d'); +// Absolute +var d3 = require(path.join(__dirname, '../fixtures/b/d')); +// Relative +var d4 = require('../fixtures/b/d'); + +assert.equal(false, false, 'testing the test program.'); + +assert.equal(true, common.indirectInstanceOf(a.A, Function)); +assert.equal('A', a.A()); + +assert.equal(true, common.indirectInstanceOf(a.C, Function)); +assert.equal('C', a.C()); + +assert.equal(true, common.indirectInstanceOf(a.D, Function)); +assert.equal('D', a.D()); + +assert.equal(true, common.indirectInstanceOf(d.D, Function)); +assert.equal('D', d.D()); + +assert.equal(true, common.indirectInstanceOf(d2.D, Function)); +assert.equal('D', d2.D()); + +assert.equal(true, common.indirectInstanceOf(d3.D, Function)); +assert.equal('D', d3.D()); + +assert.equal(true, common.indirectInstanceOf(d4.D, Function)); +assert.equal('D', d4.D()); + +assert.ok((new a.SomeClass) instanceof c.SomeClass); + +common.debug('test index.js modules ids and relative loading'); +var one = require('../fixtures/nested-index/one'), + two = require('../fixtures/nested-index/two'); +assert.notEqual(one.hello, two.hello); + +common.debug('test index.js in a folder with a trailing slash'); +var three = require('../fixtures/nested-index/three'), + threeFolder = require('../fixtures/nested-index/three/'), + threeIndex = require('../fixtures/nested-index/three/index.js'); +assert.equal(threeFolder, threeIndex); +assert.notEqual(threeFolder, three); + +common.debug('test package.json require() loading'); +assert.equal(require('../fixtures/packages/main').ok, 'ok', + 'Failed loading package'); +assert.equal(require('../fixtures/packages/main-index').ok, 'ok', + 'Failed loading package with index.js in main subdir'); + +common.debug('test cycles containing a .. path'); +var root = require('../fixtures/cycles/root'), + foo = require('../fixtures/cycles/folder/foo'); +assert.equal(root.foo, foo); +assert.equal(root.sayHello(), root.hello); + +common.debug('test node_modules folders'); +// asserts are in the fixtures files themselves, +// since they depend on the folder structure. +require('../fixtures/node_modules/foo'); + +common.debug('test name clashes'); +// this one exists and should import the local module +var my_path = require('../fixtures/path'); +assert.ok(common.indirectInstanceOf(my_path.path_func, Function)); +// this one does not exist and should throw +assert.throws(function() { require('./utils')}); + +var errorThrown = false; +try { + require('../fixtures/throws_error'); +} catch (e) { + errorThrown = true; + assert.equal('blah', e.message); +} + +assert.equal(require('path').dirname(__filename), __dirname); + +common.debug('load custom file types with extensions'); +require.extensions['.test'] = function(module, filename) { + var content = fs.readFileSync(filename).toString(); + assert.equal('this is custom source\n', content); + content = content.replace('this is custom source', + 'exports.test = \'passed\''); + module._compile(content, filename); +}; + +assert.equal(require('../fixtures/registerExt').test, 'passed'); +// unknown extension, load as .js +assert.equal(require('../fixtures/registerExt.hello.world').test, 'passed'); + +common.debug('load custom file types that return non-strings'); +require.extensions['.test'] = function(module, filename) { + module.exports = { + custom: 'passed' + }; +}; + +assert.equal(require('../fixtures/registerExt2').custom, 'passed'); + +assert.equal(require('../fixtures/foo').foo, 'ok', + 'require module with no extension'); + +assert.throws(function() { + require.paths; +}, /removed/, 'Accessing require.paths should throw.'); + +// Should not attempt to load a directory +try { + require('../fixtures/empty'); +} catch (err) { + assert.equal(err.message, 'Cannot find module \'../fixtures/empty\''); +} + +// Check load order is as expected +common.debug('load order'); + +var loadOrder = '../fixtures/module-load-order/', + msg = 'Load order incorrect.'; + +require.extensions['.reg'] = require.extensions['.js']; +require.extensions['.reg2'] = require.extensions['.js']; + +assert.equal(require(loadOrder + 'file1').file1, 'file1', msg); +assert.equal(require(loadOrder + 'file2').file2, 'file2.js', msg); +try { + require(loadOrder + 'file3'); +} catch (e) { + // Not a real .node module, but we know we require'd the right thing. + assert.ok(e.message.replace(/\\/g, '/').match(/file3\.node/)); +} +assert.equal(require(loadOrder + 'file4').file4, 'file4.reg', msg); +assert.equal(require(loadOrder + 'file5').file5, 'file5.reg2', msg); +assert.equal(require(loadOrder + 'file6').file6, 'file6/index.js', msg); +try { + require(loadOrder + 'file7'); +} catch (e) { + assert.ok(e.message.replace(/\\/g, '/').match(/file7\/index\.node/)); +} +assert.equal(require(loadOrder + 'file8').file8, 'file8/index.reg', msg); +assert.equal(require(loadOrder + 'file9').file9, 'file9/index.reg2', msg); + + +// make sure that module.require() is the same as +// doing require() inside of that module. +var parent = require('../fixtures/module-require/parent/'); +var child = require('../fixtures/module-require/child/'); +assert.equal(child.loaded, parent.loaded); + + +// #1357 Loading JSON files with require() +var json = require('../fixtures/packages/main/package.json'); +assert.deepEqual(json, { + name: 'package-name', + version: '1.2.3', + main: 'package-main-module' +}); + + +// now verify that module.children contains all the different +// modules that we've required, and that all of them contain +// the appropriate children, and so on. + +var children = module.children.reduce(function red(set, child) { + var id = path.relative(path.dirname(__dirname), child.id) + id = id.replace(/\\/g, '/'); + set[id] = child.children.reduce(red, {}); + return set; +}, {}); + +assert.deepEqual(children, { + 'common.js': {}, + 'fixtures/not-main-module.js': {}, + 'fixtures/a.js': { + 'fixtures/b/c.js': { + 'fixtures/b/d.js': {}, + 'fixtures/b/package/index.js': {} + } + }, + 'fixtures/foo': {}, + 'fixtures/nested-index/one/index.js': { + 'fixtures/nested-index/one/hello.js': {} + }, + 'fixtures/nested-index/two/index.js': { + 'fixtures/nested-index/two/hello.js': {} + }, + 'fixtures/nested-index/three.js': {}, + 'fixtures/nested-index/three/index.js': {}, + 'fixtures/packages/main/package-main-module.js': {}, + 'fixtures/packages/main-index/package-main-module/index.js': {}, + 'fixtures/cycles/root.js': { + 'fixtures/cycles/folder/foo.js': {} + }, + 'fixtures/node_modules/foo.js': { + 'fixtures/node_modules/baz/index.js': { + 'fixtures/node_modules/bar.js': {}, + 'fixtures/node_modules/baz/node_modules/asdf.js': {} + } + }, + 'fixtures/path.js': {}, + 'fixtures/throws_error.js': {}, + 'fixtures/registerExt.test': {}, + 'fixtures/registerExt.hello.world': {}, + 'fixtures/registerExt2.test': {}, + 'fixtures/empty.js': {}, + 'fixtures/module-load-order/file1': {}, + 'fixtures/module-load-order/file2.js': {}, + 'fixtures/module-load-order/file3.node': {}, + 'fixtures/module-load-order/file4.reg': {}, + 'fixtures/module-load-order/file5.reg2': {}, + 'fixtures/module-load-order/file6/index.js': {}, + 'fixtures/module-load-order/file7/index.node': {}, + 'fixtures/module-load-order/file8/index.reg': {}, + 'fixtures/module-load-order/file9/index.reg2': {}, + 'fixtures/module-require/parent/index.js': { + 'fixtures/module-require/child/index.js': { + 'fixtures/module-require/child/node_modules/target.js': {} + } + }, + 'fixtures/packages/main/package.json': {} +}); + + +// require() must take string, and must be truthy +assert.throws(function() { + console.error('require non-string'); + require({ foo: 'bar' }); +}, 'path must be a string'); + +assert.throws(function() { + console.error('require empty string'); + require(''); +}, 'missing path'); + +process.on('exit', function() { + assert.ok(common.indirectInstanceOf(a.A, Function)); + assert.equal('A done', a.A()); + + assert.ok(common.indirectInstanceOf(a.C, Function)); + assert.equal('C done', a.C()); + + assert.ok(common.indirectInstanceOf(a.D, Function)); + assert.equal('D done', a.D()); + + assert.ok(common.indirectInstanceOf(d.D, Function)); + assert.equal('D done', d.D()); + + assert.ok(common.indirectInstanceOf(d2.D, Function)); + assert.equal('D done', d2.D()); + + assert.equal(true, errorThrown); + + console.log('exit'); +}); + + +// #1440 Loading files with a byte order marker. +assert.equal(42, require('../fixtures/utf8-bom.js')); +assert.equal(42, require('../fixtures/utf8-bom.json')); diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js new file mode 100644 index 000000000..0e87c8210 --- /dev/null +++ b/test/sequential/test-net-GH-5504.js @@ -0,0 +1,128 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// this test only fails with CentOS 6.3 using kernel version 2.6.32 +// On other linuxes and darwin, the `read` call gets an ECONNRESET in +// that case. On sunos, the `write` call fails with EPIPE. +// +// However, old CentOS will occasionally send an EOF instead of a +// ECONNRESET or EPIPE when the client has been destroyed abruptly. +// +// Make sure we don't keep trying to write or read more in that case. + +switch (process.argv[2]) { + case 'server': return server(); + case 'client': return client(); + case undefined: return parent(); + default: throw new Error('wtf'); +} + +function server() { + var net = require('net'); + var content = new Buffer(64 * 1024 * 1024); + content.fill('#'); + net.createServer(function(socket) { + this.close(); + socket.on('end', function() { + console.error('end'); + }); + socket.on('_socketEnd', function() { + console.error('_socketEnd'); + }); + socket.write(content); + }).listen(common.PORT, function() { + console.log('listening'); + }); +} + +function client() { + var net = require('net'); + var client = net.connect({ + host: 'localhost', + port: common.PORT + }, function() { + client.destroy(); + }); +} + +function parent() { + var spawn = require('child_process').spawn; + var node = process.execPath; + var assert = require('assert'); + var serverExited = false; + var clientExited = false; + var serverListened = false; + var opt = { + env: { + NODE_DEBUG: 'net', + NODE_COMMON_PORT: process.env.NODE_COMMON_PORT, + } + }; + + process.on('exit', function() { + assert(serverExited); + assert(clientExited); + assert(serverListened); + console.log('ok'); + }); + + setTimeout(function() { + if (s) s.kill(); + if (c) c.kill(); + setTimeout(function() { + throw new Error('hang'); + }); + }, 4000).unref(); + + var s = spawn(node, [__filename, 'server'], opt); + var c; + + wrap(s.stderr, process.stderr, 'SERVER 2>'); + wrap(s.stdout, process.stdout, 'SERVER 1>'); + s.on('exit', function(c) { + console.error('server exited', c); + serverExited = true; + }); + + s.stdout.once('data', function() { + serverListened = true; + c = spawn(node, [__filename, 'client']); + wrap(c.stderr, process.stderr, 'CLIENT 2>'); + wrap(c.stdout, process.stdout, 'CLIENT 1>'); + c.on('exit', function(c) { + console.error('client exited', c); + clientExited = true; + }); + }); + + function wrap(inp, out, w) { + inp.setEncoding('utf8'); + inp.on('data', function(c) { + c = c.trim(); + if (!c) return; + out.write(w + c.split('\n').join('\n' + w) + '\n'); + }); + } +} + diff --git a/test/sequential/test-net-listen-exclusive-random-ports.js b/test/sequential/test-net-listen-exclusive-random-ports.js new file mode 100644 index 000000000..2c0aa4904 --- /dev/null +++ b/test/sequential/test-net-listen-exclusive-random-ports.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var cluster = require('cluster'); +var net = require('net'); + +function noop() {} + +if (cluster.isMaster) { + var worker1 = cluster.fork(); + + worker1.on('message', function(port1) { + assert.equal(port1, port1 | 0, 'first worker could not listen'); + var worker2 = cluster.fork(); + + worker2.on('message', function(port2) { + assert.equal(port2, port2 | 0, 'second worker could not listen'); + assert.notEqual(port1, port2, 'ports should not be equal'); + worker1.kill(); + worker2.kill(); + }); + }); +} else { + var server = net.createServer(noop); + + server.on('error', function(err) { + process.send(err.code); + }); + + server.listen({ + port: 0, + exclusive: true + }, function() { + process.send(server.address().port); + }); +} diff --git a/test/sequential/test-net-localport.js b/test/sequential/test-net-localport.js new file mode 100644 index 000000000..34fa377dc --- /dev/null +++ b/test/sequential/test-net-localport.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var server = net.createServer(function(socket) { + console.log(socket.remotePort); + assert.strictEqual(socket.remotePort, common.PORT + 1); + socket.end(); + socket.on('close', function() { + server.close(); + }); +}).listen(common.PORT).on('listening', function() { + var client = net.connect({ + host: '127.0.0.1', + port: common.PORT, + localPort: common.PORT + 1, + }).on('connect', function() { + assert.strictEqual(client.localPort, common.PORT + 1); + }); +}) diff --git a/test/sequential/test-net-server-address.js b/test/sequential/test-net-server-address.js new file mode 100644 index 000000000..cc8fbd211 --- /dev/null +++ b/test/sequential/test-net-server-address.js @@ -0,0 +1,125 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +// Test on IPv4 Server +var localhost_ipv4 = '127.0.0.1'; +var family_ipv4 = 'IPv4'; +var server_ipv4 = net.createServer(); + +server_ipv4.on('error', function(e) { + console.log('Error on ipv4 socket: ' + e.toString()); +}); + +server_ipv4.listen(common.PORT, localhost_ipv4, function() { + var address_ipv4 = server_ipv4.address(); + assert.strictEqual(address_ipv4.address, localhost_ipv4); + assert.strictEqual(address_ipv4.port, common.PORT); + assert.strictEqual(address_ipv4.family, family_ipv4); + server_ipv4.close(); +}); + +// Test on IPv6 Server +var localhost_ipv6 = '::1'; +var family_ipv6 = 'IPv6'; +var server_ipv6 = net.createServer(); + +server_ipv6.on('error', function(e) { + console.log('Error on ipv6 socket: ' + e.toString()); +}); + +server_ipv6.listen(common.PORT, localhost_ipv6, function() { + var address_ipv6 = server_ipv6.address(); + assert.strictEqual(address_ipv6.address, localhost_ipv6); + assert.strictEqual(address_ipv6.port, common.PORT); + assert.strictEqual(address_ipv6.family, family_ipv6); + server_ipv6.close(); +}); + +if (!common.hasIPv6) { + console.error('Skipping ipv6 part of test, no IPv6 support'); + return; +} + +// Test without hostname or ip +var anycast_ipv6 = '::'; +var server1 = net.createServer(); + +server1.on('error', function(e) { + console.log('Error on ip socket: ' + e.toString()); +}); + +// Specify the port number +server1.listen(common.PORT, function() { + var address = server1.address(); + assert.strictEqual(address.address, anycast_ipv6); + assert.strictEqual(address.port, common.PORT); + assert.strictEqual(address.family, family_ipv6); + server1.close(); +}); + +// Test without hostname or port +var server2 = net.createServer(); + +server2.on('error', function (e) { + console.log('Error on ip socket: ' + e.toString()); +}); + +// Don't specify the port number +server2.listen(function () { + var address = server2.address(); + assert.strictEqual(address.address, anycast_ipv6); + assert.strictEqual(address.family, family_ipv6); + server2.close(); +}); + +// Test without hostname, but with a false-y port +var server3 = net.createServer(); + +server3.on('error', function (e) { + console.log('Error on ip socket: ' + e.toString()); +}); + +// Specify a false-y port number +server3.listen(0, function () { + var address = server3.address(); + assert.strictEqual(address.address, anycast_ipv6); + assert.strictEqual(address.family, family_ipv6); + server3.close(); +}); + +// Test without hostname, but with port -1 +var server4 = net.createServer(); + +server4.on('error', function (e) { + console.log('Error on ip socket: ' + e.toString()); +}); + +// Specify -1 as port number +server4.listen(-1, function () { + var address = server4.address(); + assert.strictEqual(address.address, anycast_ipv6); + assert.strictEqual(address.family, family_ipv6); + server4.close(); +}); diff --git a/test/sequential/test-net-server-bind.js b/test/sequential/test-net-server-bind.js new file mode 100644 index 000000000..0951aa246 --- /dev/null +++ b/test/sequential/test-net-server-bind.js @@ -0,0 +1,95 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + + +// With only a callback, server should get a port assigned by the OS + +var address0; +var server0 = net.createServer(function(socket) { }); + +server0.listen(function() { + address0 = server0.address(); + console.log('address0 %j', address0); + server0.close(); +}); + + +// No callback to listen(), assume we can bind in 100 ms + +var address1; +var server1 = net.createServer(function(socket) { }); + +server1.listen(common.PORT); + +setTimeout(function() { + address1 = server1.address(); + console.log('address1 %j', address1); + server1.close(); +}, 100); + + +// Callback to listen() + +var address2; +var server2 = net.createServer(function(socket) { }); + +server2.listen(common.PORT + 1, function() { + address2 = server2.address(); + console.log('address2 %j', address2); + server2.close(); +}); + + +// Backlog argument + +var address3; +var server3 = net.createServer(function(socket) { }); + +server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { + address3 = server3.address(); + console.log('address3 %j', address3); + server3.close(); +}); + + +// Backlog argument without host argument + +var address4; +var server4 = net.createServer(function(socket) { }); + +server4.listen(common.PORT + 3, 127, function() { + address4 = server4.address(); + console.log('address4 %j', address4); + server4.close(); +}); + + +process.on('exit', function() { + assert.ok(address0.port > 100); + assert.equal(common.PORT, address1.port); + assert.equal(common.PORT + 1, address2.port); + assert.equal(common.PORT + 2, address3.port); + assert.equal(common.PORT + 3, address4.port); +}); diff --git a/test/sequential/test-next-tick-error-spin.js b/test/sequential/test-next-tick-error-spin.js new file mode 100644 index 000000000..e0d47a214 --- /dev/null +++ b/test/sequential/test-next-tick-error-spin.js @@ -0,0 +1,69 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +if (process.argv[2] !== 'child') { + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + stdio: 'pipe'//'inherit' + }); + var timer = setTimeout(function() { + throw new Error('child is hung'); + }, 3000); + child.on('exit', function(code) { + console.error('ok'); + assert(!code); + clearTimeout(timer); + }); +} else { + + var domain = require('domain'); + var d = domain.create(); + process.maxTickDepth = 10; + + // in the error handler, we trigger several MakeCallback events + d.on('error', function(e) { + console.log('a') + console.log('b') + console.log('c') + console.log('d') + console.log('e') + f(); + }); + + function f() { + process.nextTick(function() { + d.run(function() { + throw(new Error('x')); + }); + }); + } + + f(); + setTimeout(function () { + console.error('broke in!'); + //process.stdout.close(); + //process.stderr.close(); + process.exit(0); + }); +} diff --git a/test/sequential/test-pipe-address.js b/test/sequential/test-pipe-address.js new file mode 100644 index 000000000..6b29d2a2c --- /dev/null +++ b/test/sequential/test-pipe-address.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +var address = null; + +var server = net.createServer(function() { + assert(false); // should not be called +}); + +server.listen(common.PIPE, function() { + address = server.address(); + server.close(); +}); + +process.on('exit', function() { + assert.equal(address, common.PIPE); +}); diff --git a/test/sequential/test-pipe-head.js b/test/sequential/test-pipe-head.js new file mode 100644 index 000000000..a049be6c2 --- /dev/null +++ b/test/sequential/test-pipe-head.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var exec = require('child_process').exec; +var join = require('path').join; + +var nodePath = process.argv[0]; +var script = join(common.fixturesDir, 'print-10-lines.js'); + +var cmd = '"' + nodePath + '" "' + script + '" | head -2'; + +var finished = false; + +exec(cmd, function(err, stdout, stderr) { + if (err) throw err; + var lines = stdout.split('\n'); + assert.equal(3, lines.length); + finished = true; +}); + + +process.on('exit', function() { + assert.ok(finished); +}); diff --git a/test/sequential/test-pipe-stream.js b/test/sequential/test-pipe-stream.js new file mode 100644 index 000000000..b2b2a5518 --- /dev/null +++ b/test/sequential/test-pipe-stream.js @@ -0,0 +1,86 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +function test(clazz, cb) { + var have_ping = false; + var have_pong = false; + + function check() { + assert.ok(have_ping); + assert.ok(have_pong); + } + + function ping() { + var conn = new clazz(); + + conn.on('error', function(err) { + throw err; + }); + + conn.connect(common.PIPE, function() { + conn.write('PING', 'utf-8'); + }); + + conn.on('data', function(data) { + assert.equal(data.toString(), 'PONG'); + have_pong = true; + conn.destroy(); + }); + } + + function pong(conn) { + conn.on('error', function(err) { + throw err; + }); + + conn.on('data', function(data) { + assert.equal(data.toString(), 'PING'); + have_ping = true; + conn.write('PONG', 'utf-8'); + }); + + conn.on('close', function() { + server.close(); + }); + } + + var timeout = setTimeout(function() { + server.close(); + }, 2000); + + var server = net.Server(); + server.listen(common.PIPE, ping); + server.on('connection', pong); + server.on('close', function() { + clearTimeout(timeout); + check(); + cb && cb(); + }); +} + +test(net.Stream, function() { + test(net.Socket); +}); + diff --git a/test/sequential/test-pipe-unref.js b/test/sequential/test-pipe-unref.js new file mode 100644 index 000000000..9f715a9d1 --- /dev/null +++ b/test/sequential/test-pipe-unref.js @@ -0,0 +1,39 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var net = require('net'); +var closed = false; + +var s = net.Server(); +s.listen(common.PIPE); +s.unref(); + +setTimeout(function() { + closed = true; + s.close(); +}, 1000).unref(); + +process.on('exit', function() { + assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); +}); diff --git a/test/sequential/test-pipe.js b/test/sequential/test-pipe.js new file mode 100644 index 000000000..9f1dae885 --- /dev/null +++ b/test/sequential/test-pipe.js @@ -0,0 +1,135 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); +var net = require('net'); + +var webPort = common.PORT; +var tcpPort = webPort + 1; + +var listenCount = 0; +var gotThanks = false; +var tcpLengthSeen = 0; +var bufferSize = 5 * 1024 * 1024; + + +/* + * 5MB of random buffer. + */ +var buffer = Buffer(bufferSize); +for (var i = 0; i < buffer.length; i++) { + buffer[i] = parseInt(Math.random() * 10000) % 256; +} + + +var web = http.Server(function(req, res) { + web.close(); + + console.log(req.headers); + + var socket = net.Stream(); + socket.connect(tcpPort); + + socket.on('connect', function() { + console.log('socket connected'); + }); + + req.pipe(socket); + + req.on('end', function() { + res.writeHead(200); + res.write('thanks'); + res.end(); + console.log('response with \'thanks\''); + }); + + req.connection.on('error', function(e) { + console.log('http server-side error: ' + e.message); + process.exit(1); + }); +}); +web.listen(webPort, startClient); + + + +var tcp = net.Server(function(s) { + tcp.close(); + + console.log('tcp server connection'); + + var i = 0; + + s.on('data', function(d) { + process.stdout.write('.'); + tcpLengthSeen += d.length; + for (var j = 0; j < d.length; j++) { + assert.equal(buffer[i], d[j]); + i++; + } + }); + + s.on('end', function() { + console.log('tcp socket disconnect'); + s.end(); + }); + + s.on('error', function(e) { + console.log('tcp server-side error: ' + e.message); + process.exit(1); + }); +}); +tcp.listen(tcpPort, startClient); + + +function startClient() { + listenCount++; + if (listenCount < 2) return; + + console.log('Making request'); + + var req = http.request({ + port: common.PORT, + method: 'GET', + path: '/', + headers: { 'content-length': buffer.length } + }, function(res) { + console.log('Got response'); + res.setEncoding('utf8'); + res.on('data', function(string) { + assert.equal('thanks', string); + gotThanks = true; + }); + }); + req.write(buffer); + req.end(); + console.error('ended request', req); +} + +process.on('exit', function() { + assert.ok(gotThanks); + assert.equal(bufferSize, tcpLengthSeen); +}); + diff --git a/test/sequential/test-pump-file2tcp-noexist.js b/test/sequential/test-pump-file2tcp-noexist.js new file mode 100644 index 000000000..8017db73f --- /dev/null +++ b/test/sequential/test-pump-file2tcp-noexist.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); +var util = require('util'); +var path = require('path'); +var fn = path.join(common.fixturesDir, 'does_not_exist.txt'); + +var got_error = false; +var conn_closed = false; + +var server = net.createServer(function(stream) { + common.error('pump!'); + util.pump(fs.createReadStream(fn), stream, function(err) { + common.error('util.pump\'s callback fired'); + if (err) { + got_error = true; + } else { + common.debug('util.pump\'s callback fired with no error'); + common.debug('this shouldn\'t happen as the file doesn\'t exist...'); + assert.equal(true, false); + } + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + conn.on('data', function(chunk) { + common.error('recv data! nchars = ' + chunk.length); + buffer += chunk; + }); + + conn.on('end', function() { + conn.end(); + }); + + conn.on('close', function() { + common.error('client connection close'); + conn_closed = true; + }); +}); + +var buffer = ''; + +process.on('exit', function() { + assert.equal(true, got_error); + assert.equal(true, conn_closed); + console.log('exiting'); +}); diff --git a/test/sequential/test-pump-file2tcp.js b/test/sequential/test-pump-file2tcp.js new file mode 100644 index 000000000..60c0fdd7f --- /dev/null +++ b/test/sequential/test-pump-file2tcp.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var fs = require('fs'); +var util = require('util'); +var path = require('path'); +var fn = path.join(common.fixturesDir, 'elipses.txt'); + +var expected = fs.readFileSync(fn, 'utf8'); + +var server = net.createServer(function(stream) { + common.error('pump!'); + util.pump(fs.createReadStream(fn), stream, function() { + common.error('server stream close'); + common.error('server close'); + server.close(); + }); +}); + +server.listen(common.PORT, function() { + var conn = net.createConnection(common.PORT); + conn.setEncoding('utf8'); + conn.on('data', function(chunk) { + common.error('recv data! nchars = ' + chunk.length); + buffer += chunk; + }); + + conn.on('end', function() { + conn.end(); + }); + conn.on('close', function() { + common.error('client connection close'); + }); +}); + +var buffer = ''; +var count = 0; + +server.on('listening', function() { +}); + +process.on('exit', function() { + assert.equal(expected, buffer); +}); diff --git a/test/sequential/test-readdir.js b/test/sequential/test-readdir.js new file mode 100644 index 000000000..24997241f --- /dev/null +++ b/test/sequential/test-readdir.js @@ -0,0 +1,91 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var got_error = false, + readdirDir = path.join(common.fixturesDir, 'readdir'); + +var files = ['are', + 'dir', + 'empty', + 'files', + 'for', + 'just', + 'testing.js', + 'these']; + + +console.log('readdirSync ' + readdirDir); +var f = fs.readdirSync(readdirDir); +console.dir(f); +assert.deepEqual(files, f.sort()); + + +console.log('readdir ' + readdirDir); +fs.readdir(readdirDir, function(err, f) { + if (err) { + console.log('error'); + got_error = true; + } else { + console.dir(f); + assert.deepEqual(files, f.sort()); + } +}); + +process.on('exit', function() { + assert.equal(false, got_error); + console.log('exit'); +}); + + +// readdir() on file should throw ENOTDIR +// https://github.com/joyent/node/issues/1869 +(function() { + var has_caught = false; + + try { + fs.readdirSync(__filename); + } + catch (e) { + has_caught = true; + assert.equal(e.code, 'ENOTDIR'); + } + + assert(has_caught); +})(); + + +(function() { + var readdir_cb_called = false; + + fs.readdir(__filename, function(e) { + readdir_cb_called = true; + assert.equal(e.code, 'ENOTDIR'); + }); + + process.on('exit', function() { + assert(readdir_cb_called); + }); +})(); diff --git a/test/sequential/test-regress-GH-1531.js b/test/sequential/test-regress-GH-1531.js new file mode 100644 index 000000000..53bc2a3ca --- /dev/null +++ b/test/sequential/test-regress-GH-1531.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +if (!process.versions.openssl) { + console.error('Skipping because node compiled without OpenSSL.'); + process.exit(0); +} + +var https = require('https'); +var assert = require('assert'); +var fs = require('fs'); +var common = require('../common'); + +var options = { + key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') +}; + +var gotCallback = false; + +var server = https.createServer(options, function(req, res) { + res.writeHead(200); + res.end('hello world\n'); +}); + +server.listen(common.PORT, function() { + console.error('listening'); + https.get({ + agent: false, + path: '/', + port: common.PORT, + rejectUnauthorized: false + }, function(res) { + console.error(res.statusCode, res.headers); + gotCallback = true; + res.resume(); + server.close(); + }).on('error', function(e) { + console.error(e.stack); + process.exit(1); + }); +}); + +process.on('exit', function() { + assert.ok(gotCallback); + console.log('ok'); +}); + diff --git a/test/sequential/test-regress-GH-1697.js b/test/sequential/test-regress-GH-1697.js new file mode 100644 index 000000000..fdf2c42e9 --- /dev/null +++ b/test/sequential/test-regress-GH-1697.js @@ -0,0 +1,70 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'), + cp = require('child_process'), + util = require('util'); + +if (process.argv[2] === 'server') { + // Server + + var server = net.createServer(function(conn) { + conn.on('data', function(data) { + console.log('server received ' + data.length + ' bytes'); + }); + + conn.on('close', function() { + server.close(); + }); + }); + + server.listen(common.PORT, '127.0.0.1', function() { + console.log('Server running.'); + }); + +} else { + // Client + + var serverProcess = cp.spawn(process.execPath, [process.argv[1], 'server']); + serverProcess.stdout.pipe(process.stdout); + serverProcess.stderr.pipe(process.stdout); + + serverProcess.stdout.once('data', function() { + var client = net.createConnection(common.PORT, '127.0.0.1'); + client.on('connect', function() { + var alot = new Buffer(1024), + alittle = new Buffer(1); + + for (var i = 0; i < 100; i++) { + client.write(alot); + } + + // Block the event loop for 1 second + var start = (new Date()).getTime(); + while ((new Date).getTime() < start + 1000) {} + + client.write(alittle); + + client.destroySoon(); + }); + }); +} diff --git a/test/sequential/test-regress-GH-1726.js b/test/sequential/test-regress-GH-1726.js new file mode 100644 index 000000000..f65e63d10 --- /dev/null +++ b/test/sequential/test-regress-GH-1726.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// 'Software'), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Open a chain of five Node processes each a child of the next. The final +// process exits immediately. Each process in the chain is instructed to +// exit when its child exits. +// https://github.com/joyent/node/issues/1726 + +var common = require('../common'); +var assert = require('assert'); +var ch = require('child_process'); + +var gen = +(process.argv[2] || 0); +var maxGen = 5; + + +if (gen === maxGen) { + console.error('hit maxGen, exiting', maxGen); + return; +} + +var child = ch.spawn(process.execPath, [__filename, gen + 1], { + stdio: [ 'ignore', 'pipe', 'ignore' ] +}); +assert.ok(!child.stdin); +assert.ok(child.stdout); +assert.ok(!child.stderr); + +console.error('gen=%d, pid=%d', gen, process.pid); + +/* +var timer = setTimeout(function () { + throw new Error('timeout! gen='+gen); +}, 1000); +*/ + +child.on('exit', function(code) { + console.error('exit %d from gen %d', code, gen + 1); + //clearTimeout(timer); +}); + +child.stdout.pipe(process.stdout); + +child.stdout.on('close', function() { + console.error('child.stdout close gen=%d', gen); +}); diff --git a/test/sequential/test-regress-GH-1899.js b/test/sequential/test-regress-GH-1899.js new file mode 100644 index 000000000..7fc8007a2 --- /dev/null +++ b/test/sequential/test-regress-GH-1899.js @@ -0,0 +1,40 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var path = require('path'); +var assert = require('assert'); +var spawn = require('child_process').spawn; +var common = require('../common'); + +var child = spawn(process.argv[0], [ + path.join(common.fixturesDir, 'GH-1899-output.js') +]); +var output = ''; + +child.stdout.on('data', function(data) { + output += data; +}); + +child.on('exit', function(code, signal) { + assert.equal(code, 0); + assert.equal(output, 'hello, world!\n'); +}); + diff --git a/test/sequential/test-regress-GH-3542.js b/test/sequential/test-regress-GH-3542.js new file mode 100644 index 000000000..90e0b7850 --- /dev/null +++ b/test/sequential/test-regress-GH-3542.js @@ -0,0 +1,54 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This test is only relevant on Windows. +if (process.platform !== 'win32') { + return process.exit(0); +} + +var common = require('../common.js'), + assert = require('assert'), + fs = require('fs'), + path = require('path'), + succeeded = 0; + +function test(p) { + var result = fs.realpathSync(p); + assert.strictEqual(result, path.resolve(p)); + + fs.realpath(p, function(err, result) { + assert.ok(!err); + assert.strictEqual(result, path.resolve(p)); + succeeded++; + }); +} + +test('//localhost/c$/windows/system32'); +test('//localhost/c$/windows'); +test('//localhost/c$/') +test('\\\\localhost\\c$') +test('c:\\'); +test('c:'); +test(process.env.windir); + +process.on('exit', function() { + assert.strictEqual(succeeded, 7); +}); \ No newline at end of file diff --git a/test/sequential/test-regress-GH-3739.js b/test/sequential/test-regress-GH-3739.js new file mode 100644 index 000000000..937068795 --- /dev/null +++ b/test/sequential/test-regress-GH-3739.js @@ -0,0 +1,66 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'), + assert = require('assert'), + fs = require('fs'), + path = require('path'); + +var dir = path.resolve(common.fixturesDir), + dirs = []; + +// Make a long path. +for (var i = 0; i < 50; i++) { + dir = dir + '/123456790'; + try { + fs.mkdirSync(dir, '0777'); + } catch (e) { + if (e.code == 'EEXIST') { + // Ignore; + } else { + cleanup(); + throw e; + } + } + dirs.push(dir); +} + +// Test existsSync +var r = fs.existsSync(dir); +if (r !== true) { + cleanup(); + throw new Error('fs.existsSync returned false'); +} + +// Text exists +fs.exists(dir, function(r) { + cleanup(); + if (r !== true) { + throw new Error('fs.exists reported false'); + } +}); + +// Remove all created directories +function cleanup() { + for (var i = dirs.length - 1; i >= 0; i--) { + fs.rmdirSync(dirs[i]); + } +} diff --git a/test/sequential/test-regress-GH-4015.js b/test/sequential/test-regress-GH-4015.js new file mode 100644 index 000000000..b66584f80 --- /dev/null +++ b/test/sequential/test-regress-GH-4015.js @@ -0,0 +1,33 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +var cmd = process.execPath + + ' ' + + common.fixturesDir + + '/test-regress-GH-4015.js'; + +exec(cmd, function(err, stdout, stderr) { + assert(/RangeError: Maximum call stack size exceeded/.test(stderr)); +}); diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js new file mode 100644 index 000000000..3dff1684d --- /dev/null +++ b/test/sequential/test-regress-GH-4027.js @@ -0,0 +1,41 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var filename = path.join(common.tmpDir, 'watched'); +fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); +setTimeout(fs.unlinkSync, 100, filename); + +var seenEvent = 0; +process.on('exit', function() { + assert.equal(seenEvent, 1); +}); + +fs.watchFile(filename, { interval: 50 }, function(curr, prev) { + assert.equal(prev.nlink, 1); + assert.equal(curr.nlink, 0); + fs.unwatchFile(filename); + seenEvent++; +}); diff --git a/test/sequential/test-regress-GH-4948.js b/test/sequential/test-regress-GH-4948.js new file mode 100644 index 000000000..5e717fad5 --- /dev/null +++ b/test/sequential/test-regress-GH-4948.js @@ -0,0 +1,62 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// https://github.com/joyent/node/issues/4948 + +var common = require('../common'); +var http = require('http'); + +var reqCount = 0; +var server = http.createServer(function(serverReq, serverRes){ + if (reqCount) { + serverRes.end(); + server.close(); + return; + } + reqCount = 1; + + + // normally the use case would be to call an external site + // does not require connecting locally or to itself to fail + var r = http.request({hostname: 'localhost', port: common.PORT}, function(res) { + // required, just needs to be in the client response somewhere + serverRes.end(); + + // required for test to fail + res.on('data', function(data) { }); + + }); + r.on('error', function(e) {}); + r.end(); + + serverRes.write('some data'); +}).listen(common.PORT); + +// simulate a client request that closes early +var net = require('net'); + +var sock = new net.Socket(); +sock.connect(common.PORT, 'localhost'); + +sock.on('connect', function() { + sock.write('GET / HTTP/1.1\r\n\r\n'); + sock.end(); +}); \ No newline at end of file diff --git a/test/sequential/test-regress-GH-746.js b/test/sequential/test-regress-GH-746.js new file mode 100644 index 000000000..29f145652 --- /dev/null +++ b/test/sequential/test-regress-GH-746.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Just test that destroying stdin doesn't mess up listening on a server. +// This is a regression test for GH-746. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); + +process.stdin.destroy(); + +var accepted = null; +var server = net.createServer(function(socket) { + console.log('accepted'); + accepted = socket; + socket.end(); + server.close(); +}); + + +server.listen(common.PORT, function() { + console.log('listening...'); + + net.createConnection(common.PORT); +}); + + +process.on('exit', function() { + assert.ok(accepted); +}); + diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js new file mode 100644 index 000000000..c2039a9c6 --- /dev/null +++ b/test/sequential/test-regress-GH-784.js @@ -0,0 +1,157 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Regression test for GH-784 +// https://github.com/joyent/node/issues/784 +// +// The test works by making a total of 8 requests to the server. The first +// two are made with the server off - they should come back as ECONNREFUSED. +// The next two are made with server on - they should come back successful. +// The next two are made with the server off - and so on. Without the fix +// we were experiencing parse errors and instead of ECONNREFUSED. +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + + +var server = http.createServer(function(req, res) { + var body = ''; + + req.setEncoding('utf8'); + req.on('data', function(chunk) { + body += chunk; + }); + + req.on('end', function() { + assert.equal('PING', body); + res.writeHead(200); + res.end('PONG'); + }); +}); + + +server.on('listening', pingping); + + +function serverOn() { + console.error('Server ON'); + server.listen(common.PORT); +} + + +function serverOff() { + console.error('Server OFF'); + server.close(); + pingping(); +} + +var responses = []; + + +function afterPing(result) { + responses.push(result); + console.error('afterPing. responses.length = ' + responses.length); + switch (responses.length) { + case 2: + assert.ok(/ECONNREFUSED/.test(responses[0])); + assert.ok(/ECONNREFUSED/.test(responses[1])); + serverOn(); + break; + + case 4: + assert.ok(/success/.test(responses[2])); + assert.ok(/success/.test(responses[3])); + serverOff(); + break; + + case 6: + assert.ok(/ECONNREFUSED/.test(responses[4])); + assert.ok(/ECONNREFUSED/.test(responses[5])); + serverOn(); + break; + + case 8: + assert.ok(/success/.test(responses[6])); + assert.ok(/success/.test(responses[7])); + server.close(); + // we should go to process.on('exit') from here. + break; + } +} + + +function ping() { + console.error('making req'); + + var opt = { + port: common.PORT, + path: '/ping', + method: 'POST' + }; + + var req = http.request(opt, function(res) { + var body = ''; + + res.setEncoding('utf8'); + res.on('data', function(chunk) { + body += chunk; + }); + + res.on('end', function() { + assert.equal('PONG', body); + assert.ok(!hadError); + gotEnd = true; + afterPing('success'); + }); + }); + + req.end('PING'); + + var gotEnd = false; + var hadError = false; + + req.on('error', function(error) { + console.log('Error making ping req: ' + error); + hadError = true; + assert.ok(!gotEnd); + afterPing(error.message); + }); +} + + + +function pingping() { + ping(); + ping(); +} + + +pingping(); + + + + +process.on('exit', function() { + console.error("process.on('exit')"); + console.error(responses); + + assert.equal(8, responses.length); +}); diff --git a/test/sequential/test-regress-GH-819.js b/test/sequential/test-regress-GH-819.js new file mode 100644 index 000000000..874d99e28 --- /dev/null +++ b/test/sequential/test-regress-GH-819.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var net = require('net'); +var assert = require('assert'); + +// Connect to something that we need to DNS resolve +var c = net.createConnection(80, 'google.com'); +c.destroy(); diff --git a/test/sequential/test-regress-GH-877.js b/test/sequential/test-regress-GH-877.js new file mode 100644 index 000000000..30e1f8009 --- /dev/null +++ b/test/sequential/test-regress-GH-877.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var http = require('http'); +var assert = require('assert'); + +var N = 20; +var responses = 0; +var maxQueued = 0; + +var agent = http.globalAgent; +agent.maxSockets = 10; + +var server = http.createServer(function(req, res) { + res.writeHead(200); + res.end('Hello World\n'); +}); + +var addrString = agent.getName({ host: '127.0.0.1', port: common.PORT }); + +server.listen(common.PORT, '127.0.0.1', function() { + for (var i = 0; i < N; i++) { + var options = { + host: '127.0.0.1', + port: common.PORT + }; + + var req = http.get(options, function(res) { + if (++responses == N) { + server.close(); + } + res.resume(); + }); + + assert.equal(req.agent, agent); + + console.log('Socket: ' + agent.sockets[addrString].length + '/' + + agent.maxSockets + ' queued: ' + (agent.requests[addrString] ? + agent.requests[addrString].length : 0)); + + var agentRequests = agent.requests[addrString] ? + agent.requests[addrString].length : 0; + + if (maxQueued < agentRequests) { + maxQueued = agentRequests; + } + } +}); + +process.on('exit', function() { + assert.ok(responses == N); + assert.ok(maxQueued <= 10); +}); diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js new file mode 100644 index 000000000..c2c6c0655 --- /dev/null +++ b/test/sequential/test-require-cache-without-stat.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// We've experienced a regression where the module loader stats a bunch of +// directories on require() even if it's been called before. The require() +// should caching the request. +var common = require('../common'); +var fs = require('fs'); +var assert = require('assert'); + +var counter = 0; + +// Switch out the two stat implementations so that they increase a counter +// each time they are called. + +var _statSync = fs.statSync; +var _stat = fs.stat; + +fs.statSync = function() { + counter++; + return _statSync.apply(this, arguments); +}; + +fs.stat = function() { + counter++; + return _stat.apply(this, arguments); +}; + +// Load the module 'a' and 'http' once. It should become cached. +require(common.fixturesDir + '/a'); +require('../fixtures/a.js'); +require('./../fixtures/a.js'); +require('http'); + +console.log('counterBefore = %d', counter); +var counterBefore = counter; + +// Now load the module a bunch of times with equivalent paths. +// stat should not be called. +for (var i = 0; i < 100; i++) { + require(common.fixturesDir + '/a'); + require('../fixtures/a.js'); + require('./../fixtures/a.js'); +} + +// Do the same with a built-in module +for (var i = 0; i < 100; i++) { + require('http'); +} + +console.log('counterAfter = %d', counter); +var counterAfter = counter; + +assert.equal(counterBefore, counterAfter); diff --git a/test/sequential/test-setproctitle.js b/test/sequential/test-setproctitle.js new file mode 100644 index 000000000..6373af4cd --- /dev/null +++ b/test/sequential/test-setproctitle.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Original test written by Jakub Lekstan + +// FIXME add sunos support +if ('linux freebsd darwin'.indexOf(process.platform) === -1) { + console.error('Skipping test, platform not supported.'); + process.exit(); +} + +var common = require('../common'); +var assert = require('assert'); +var exec = require('child_process').exec; + +// The title shouldn't be too long; libuv's uv_set_process_title() out of +// security considerations no longer overwrites envp, only argv, so the +// maximum title length is possibly quite short. +var title = 'testme'; + +assert.notEqual(process.title, title); +process.title = title; +assert.equal(process.title, title); + +exec('ps -p ' + process.pid + ' -o args=', function(error, stdout, stderr) { + assert.equal(error, null); + assert.equal(stderr, ''); + + // freebsd always add ' (procname)' to the process title + if (process.platform === 'freebsd') title += ' (node)'; + + // omitting trailing whitespace and \n + assert.equal(stdout.replace(/\s+$/, ''), title); +}); diff --git a/test/sequential/test-sigint-infinite-loop.js b/test/sequential/test-sigint-infinite-loop.js new file mode 100644 index 000000000..4ff274584 --- /dev/null +++ b/test/sequential/test-sigint-infinite-loop.js @@ -0,0 +1,61 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +// This test is to assert that we can SIGINT a script which loops forever. +// Ref(http): +// groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f +var common = require('../common'); +var assert = require('assert'); +var spawn = require('child_process').spawn; + +console.log('start'); + +var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); + +var sentKill = false; +var gotChildExit = true; + +c.stdout.on('data', function(s) { + // Prevent race condition: + // Wait for the first bit of output from the child process + // so that we're sure that it's in the V8 event loop and not + // just in the startup phase of execution. + if (!sentKill) { + c.kill('SIGINT'); + console.log('SIGINT infinite-loop.js'); + sentKill = true; + } +}); + +c.on('exit', function(code) { + assert.ok(code !== 0); + console.log('killed infinite-loop.js'); + gotChildExit = true; +}); + +process.on('exit', function() { + assert.ok(sentKill); + assert.ok(gotChildExit); +}); + diff --git a/test/sequential/test-signal-unregister.js b/test/sequential/test-signal-unregister.js new file mode 100644 index 000000000..d65e0a0d9 --- /dev/null +++ b/test/sequential/test-signal-unregister.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); + +var childKilled = false, done = false, + spawn = require('child_process').spawn, + util = require('util'), + child; + +var join = require('path').join; + +child = spawn(process.argv[0], [join(common.fixturesDir, 'should_exit.js')]); +child.on('exit', function() { + if (!done) childKilled = true; +}); + +setTimeout(function() { + console.log('Sending SIGINT'); + child.kill('SIGINT'); + setTimeout(function() { + console.log('Chance has been given to die'); + done = true; + if (!childKilled) { + // Cleanup + console.log('Child did not die on SIGINT, sending SIGTERM'); + child.kill('SIGTERM'); + } + }, 200); +}, 200); + +process.on('exit', function() { + assert.ok(childKilled); +}); diff --git a/test/sequential/test-socket-write-after-fin-error.js b/test/sequential/test-socket-write-after-fin-error.js new file mode 100644 index 000000000..123557417 --- /dev/null +++ b/test/sequential/test-socket-write-after-fin-error.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// This is similar to simple/test-socket-write-after-fin, except that +// we don't set allowHalfOpen. Then we write after the client has sent +// a FIN, and this is an error. However, the standard "write after end" +// message is too vague, and doesn't actually tell you what happens. + +var net = require('net'); +var serverData = ''; +var gotServerEnd = false; +var clientData = ''; +var gotClientEnd = false; +var gotServerError = false; + +var server = net.createServer(function(sock) { + sock.setEncoding('utf8'); + sock.on('error', function(er) { + console.error(er.code + ': ' + er.message); + gotServerError = er; + }); + + sock.on('data', function(c) { + serverData += c; + }); + sock.on('end', function() { + gotServerEnd = true + sock.write(serverData); + sock.end(); + }); + server.close(); +}); +server.listen(common.PORT); + +var sock = net.connect(common.PORT); +sock.setEncoding('utf8'); +sock.on('data', function(c) { + clientData += c; +}); + +sock.on('end', function() { + gotClientEnd = true; +}); + +process.on('exit', function() { + assert.equal(clientData, ''); + assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); + assert(gotClientEnd); + assert(gotServerEnd); + assert(gotServerError); + assert.equal(gotServerError.code, 'EPIPE'); + assert.notEqual(gotServerError.message, 'write after end'); + console.log('ok'); +}); + +sock.write('hello1'); +sock.write('hello2'); +sock.write('hello3\n'); +sock.end('THUNDERMUSCLE!'); diff --git a/test/sequential/test-socket-write-after-fin.js b/test/sequential/test-socket-write-after-fin.js new file mode 100644 index 000000000..88d780b81 --- /dev/null +++ b/test/sequential/test-socket-write-after-fin.js @@ -0,0 +1,64 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var serverData = ''; +var gotServerEnd = false; +var clientData = ''; +var gotClientEnd = false; + +var server = net.createServer({ allowHalfOpen: true }, function(sock) { + sock.setEncoding('utf8'); + sock.on('data', function(c) { + serverData += c; + }); + sock.on('end', function() { + gotServerEnd = true + sock.end(serverData); + server.close(); + }); +}); +server.listen(common.PORT); + +var sock = net.connect(common.PORT); +sock.setEncoding('utf8'); +sock.on('data', function(c) { + clientData += c; +}); + +sock.on('end', function() { + gotClientEnd = true; +}); + +process.on('exit', function() { + assert.equal(serverData, clientData); + assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); + assert(gotClientEnd); + assert(gotServerEnd); + console.log('ok'); +}); + +sock.write('hello1'); +sock.write('hello2'); +sock.write('hello3\n'); +sock.end('THUNDERMUSCLE!'); diff --git a/test/sequential/test-stdin-child-proc.js b/test/sequential/test-stdin-child-proc.js new file mode 100644 index 000000000..6a4ea9473 --- /dev/null +++ b/test/sequential/test-stdin-child-proc.js @@ -0,0 +1,28 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests that pausing and resuming stdin does not hang and timeout +// when done in a child process. See test/simple/test-stdin-pause-resume.js +var common = require('../common'); +var child_process = require('child_process'); +var path = require('path'); +child_process.spawn(process.execPath, + [path.resolve(__dirname, 'test-stdin-pause-resume.js')]); diff --git a/test/sequential/test-stdin-from-file.js b/test/sequential/test-stdin-from-file.js new file mode 100644 index 000000000..617b9037d --- /dev/null +++ b/test/sequential/test-stdin-from-file.js @@ -0,0 +1,65 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var join = require('path').join; +var childProccess = require('child_process'); +var fs = require('fs'); + +var stdoutScript = join(common.fixturesDir, 'echo-close-check.js'); +var tmpFile = join(common.fixturesDir, 'stdin.txt'); + +var cmd = '"' + process.argv[0] + '" "' + stdoutScript + '" < "' + + tmpFile + '"'; + +var string = 'abc\nümlaut.\nsomething else\n' + + '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,' + + '疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、' + + '云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + + '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + + '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + + '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + + '采用封建制和郡县制并存的制度,' + + '它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + + '有效的改善了岭南地区落后的政治、##济现状。\n'; + + +console.log(cmd + '\n\n'); + +try { + fs.unlinkSync(tmpFile); +} catch (e) {} + +fs.writeFileSync(tmpFile, string); + +childProccess.exec(cmd, function(err, stdout, stderr) { + fs.unlinkSync(tmpFile); + + if (err) throw err; + console.log(stdout); + assert.equal(stdout, 'hello world\r\n' + string); + assert.equal('', stderr); +}); diff --git a/test/sequential/test-stdin-pipe-resume.js b/test/sequential/test-stdin-pipe-resume.js new file mode 100644 index 000000000..163d8369c --- /dev/null +++ b/test/sequential/test-stdin-pipe-resume.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// This tests that piping stdin will cause it to resume() as well. +var common = require('../common'); +var assert = require('assert'); + +if (process.argv[2] === 'child') { + process.stdin.pipe(process.stdout); +} else { + var spawn = require('child_process').spawn; + var buffers = []; + var child = spawn(process.execPath, [__filename, 'child']); + child.stdout.on('data', function(c) { + buffers.push(c); + }); + child.stdout.on('close', function() { + var b = Buffer.concat(buffers).toString(); + assert.equal(b, 'Hello, world\n'); + console.log('ok'); + }); + child.stdin.write('Hel'); + child.stdin.write('lo,'); + child.stdin.write(' wo'); + setTimeout(function() { + child.stdin.write('rld\n'); + child.stdin.end(); + }, 10); +} + diff --git a/test/sequential/test-stdin-script-child.js b/test/sequential/test-stdin-script-child.js new file mode 100644 index 000000000..e940c3c3f --- /dev/null +++ b/test/sequential/test-stdin-script-child.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var spawn = require('child_process').spawn; +var child = spawn(process.execPath, [], { + env: { + NODE_DEBUG: process.argv[2] + } +}); +var wanted = child.pid + '\n'; +var found = ''; + +child.stdout.setEncoding('utf8'); +child.stdout.on('data', function(c) { + found += c; +}); + +child.stderr.setEncoding('utf8'); +child.stderr.on('data', function(c) { + console.error('> ' + c.trim().split(/\n/).join('\n> ')); +}); + +child.on('close', function(c) { + assert(!c); + assert.equal(found, wanted); + console.log('ok'); +}); + +setTimeout(function() { + child.stdin.end('console.log(process.pid)'); +}); diff --git a/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js b/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js new file mode 100644 index 000000000..2e79c5af1 --- /dev/null +++ b/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +if (process.argv[2] === 'child') + process.stdout.end('foo'); +else + parent(); + +function parent() { + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child']); + var out = ''; + var err = ''; + + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + + child.stdout.on('data', function(c) { + out += c; + }); + child.stderr.on('data', function(c) { + err += c; + }); + + child.on('close', function(code, signal) { + assert(code); + assert.equal(out, 'foo'); + assert(/process\.stdout cannot be closed/.test(err)); + console.log('ok'); + }); +} diff --git a/test/sequential/test-stdout-close-catch.js b/test/sequential/test-stdout-close-catch.js new file mode 100644 index 000000000..f517a6cbe --- /dev/null +++ b/test/sequential/test-stdout-close-catch.js @@ -0,0 +1,56 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var child_process = require('child_process'); +var fs = require('fs'); + +var testScript = path.join(common.fixturesDir, 'catch-stdout-error.js'); + +var cmd = JSON.stringify(process.execPath) + ' ' + + JSON.stringify(testScript) + ' | ' + + JSON.stringify(process.execPath) + ' ' + + '-pe "process.exit(1);"'; + +var child = child_process.exec(cmd); +var output = ''; +var outputExpect = { 'code': 'EPIPE', + 'errno': 'EPIPE', + 'syscall': 'write' }; + +child.stderr.on('data', function(c) { + output += c; +}); + +child.on('close', function(code) { + try { + output = JSON.parse(output); + } catch (er) { + console.error(output); + process.exit(1); + } + + assert.deepEqual(output, outputExpect); + console.log('ok'); +}); diff --git a/test/sequential/test-stdout-stderr-reading.js b/test/sequential/test-stdout-stderr-reading.js new file mode 100644 index 000000000..5b67a0d06 --- /dev/null +++ b/test/sequential/test-stdout-stderr-reading.js @@ -0,0 +1,94 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +// verify that stdout is never read from. +var net = require('net'); +var read = net.Socket.prototype.read; + +net.Socket.prototype.read = function() { + if (this.fd === 1) + throw new Error('reading from stdout!'); + if (this.fd === 2) + throw new Error('reading from stderr!'); + return read.apply(this, arguments); +}; + +if (process.argv[2] === 'child') + child(); +else + parent(); + +function parent() { + var spawn = require('child_process').spawn; + var node = process.execPath; + var closes = 0; + + var c1 = spawn(node, [__filename, 'child']); + var c1out = ''; + c1.stdout.setEncoding('utf8'); + c1.stdout.on('data', function(chunk) { + c1out += chunk; + }); + c1.stderr.setEncoding('utf8'); + c1.stderr.on('data', function(chunk) { + console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); + }); + c1.on('close', function(code, signal) { + closes++; + assert(!code); + assert(!signal); + assert.equal(c1out, 'ok\n'); + console.log('ok'); + }); + + var c2 = spawn(node, ['-e', 'console.log("ok")']); + var c2out = ''; + c2.stdout.setEncoding('utf8'); + c2.stdout.on('data', function(chunk) { + c2out += chunk; + }); + c1.stderr.setEncoding('utf8'); + c1.stderr.on('data', function(chunk) { + console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); + }); + c2.on('close', function(code, signal) { + closes++; + assert(!code); + assert(!signal); + assert.equal(c2out, 'ok\n'); + console.log('ok'); + }); + + process.on('exit', function() { + assert.equal(closes, 2, 'saw both closes'); + }); +} + +function child() { + // should not be reading *ever* in here. + net.Socket.prototype.read = function() { + throw new Error('no reading allowed in child'); + }; + console.log('ok'); +} diff --git a/test/sequential/test-stdout-to-file.js b/test/sequential/test-stdout-to-file.js new file mode 100644 index 000000000..94181ef81 --- /dev/null +++ b/test/sequential/test-stdout-to-file.js @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var childProccess = require('child_process'); +var fs = require('fs'); + +var scriptString = path.join(common.fixturesDir, 'print-chars.js'); +var scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js'); +var tmpFile = path.join(common.tmpDir, 'stdout.txt'); + +function test(size, useBuffer, cb) { + var cmd = '"' + process.argv[0] + '"' + + ' ' + + '"' + (useBuffer ? scriptBuffer : scriptString) + '"' + + ' ' + + size + + ' > ' + + '"' + tmpFile + '"'; + + try { + fs.unlinkSync(tmpFile); + } catch (e) {} + + common.print(size + ' chars to ' + tmpFile + '...'); + + childProccess.exec(cmd, function(err) { + if (err) throw err; + + console.log('done!'); + + var stat = fs.statSync(tmpFile); + + console.log(tmpFile + ' has ' + stat.size + ' bytes'); + + assert.equal(size, stat.size); + fs.unlinkSync(tmpFile); + + cb(); + }); +} + +var finished = false; +test(1024 * 1024, false, function() { + console.log('Done printing with string'); + test(1024 * 1024, true, function() { + console.log('Done printing with buffer'); + finished = true; + }); +}); + +process.on('exit', function() { + assert.ok(finished); +}); diff --git a/test/sequential/test-stream2-fs.js b/test/sequential/test-stream2-fs.js new file mode 100644 index 000000000..e16240628 --- /dev/null +++ b/test/sequential/test-stream2-fs.js @@ -0,0 +1,72 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +var common = require('../common.js'); +var R = require('_stream_readable'); +var assert = require('assert'); + +var fs = require('fs'); +var FSReadable = fs.ReadStream; + +var path = require('path'); +var file = path.resolve(common.fixturesDir, 'x1024.txt'); + +var size = fs.statSync(file).size; + +var expectLengths = [1024]; + +var util = require('util'); +var Stream = require('stream'); + +util.inherits(TestWriter, Stream); + +function TestWriter() { + Stream.apply(this); + this.buffer = []; + this.length = 0; +} + +TestWriter.prototype.write = function(c) { + this.buffer.push(c.toString()); + this.length += c.length; + return true; +}; + +TestWriter.prototype.end = function(c) { + if (c) this.buffer.push(c.toString()); + this.emit('results', this.buffer); +} + +var r = new FSReadable(file); +var w = new TestWriter(); + +w.on('results', function(res) { + console.error(res, w.length); + assert.equal(w.length, size); + var l = 0; + assert.deepEqual(res.map(function (c) { + return c.length; + }), expectLengths); + console.log('ok'); +}); + +r.pipe(w); diff --git a/test/sequential/test-stream2-httpclient-response-end.js b/test/sequential/test-stream2-httpclient-response-end.js new file mode 100644 index 000000000..15cffc2ac --- /dev/null +++ b/test/sequential/test-stream2-httpclient-response-end.js @@ -0,0 +1,52 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common.js'); +var assert = require('assert'); +var http = require('http'); +var msg = 'Hello'; +var readable_event = false; +var end_event = false; +var server = http.createServer(function(req, res) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(msg); +}).listen(common.PORT, function() { + http.get({port: common.PORT}, function(res) { + var data = ''; + res.on('readable', function() { + console.log('readable event'); + readable_event = true; + data += res.read(); + }); + res.on('end', function() { + console.log('end event'); + end_event = true; + assert.strictEqual(msg, data); + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert(readable_event); + assert(end_event); +}); + diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js new file mode 100644 index 000000000..9e2d3ec22 --- /dev/null +++ b/test/sequential/test-stream2-stderr-sync.js @@ -0,0 +1,97 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Make sure that sync writes to stderr get processed before exiting. + +var common = require('../common.js'); +var assert = require('assert'); +var util = require('util'); + +var errnoException = util._errnoException; + +function parent() { + var spawn = require('child_process').spawn; + var assert = require('assert'); + var i = 0; + children.forEach(function(_, c) { + var child = spawn(process.execPath, [__filename, '' + c]); + var err = ''; + + child.stderr.on('data', function(c) { + err += c; + }); + + child.on('close', function() { + assert.equal(err, 'child ' + c + '\nfoo\nbar\nbaz\n'); + console.log('ok %d child #%d', ++i, c); + if (i === children.length) + console.log('1..' + i); + }); + }); +} + +// using console.error +function child0() { + console.error('child 0'); + console.error('foo'); + console.error('bar'); + console.error('baz'); +} + +// using process.stderr +function child1() { + process.stderr.write('child 1\n'); + process.stderr.write('foo\n'); + process.stderr.write('bar\n'); + process.stderr.write('baz\n'); +} + +// using a net socket +function child2() { + var net = require('net'); + var socket = new net.Socket({ + fd: 2, + readable: false, + writable: true}); + socket.write('child 2\n'); + socket.write('foo\n'); + socket.write('bar\n'); + socket.write('baz\n'); +} + + +function child3() { + console.error('child 3\nfoo\nbar\nbaz'); +} + +function child4() { + process.stderr.write('child 4\nfoo\nbar\nbaz\n'); +} + +var children = [ child0, child1, child2, child3, child4 ]; + +if (!process.argv[2]) { + parent(); +} else { + children[process.argv[2]](); + // immediate process.exit to kill any waiting stuff. + process.exit(); +} diff --git a/test/sequential/test-sync-fileread.js b/test/sequential/test-sync-fileread.js new file mode 100644 index 000000000..428838a8c --- /dev/null +++ b/test/sequential/test-sync-fileread.js @@ -0,0 +1,32 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var fs = require('fs'); + +var fixture = path.join(__dirname, '../fixtures/x.txt'); + +assert.equal('xyz\n', fs.readFileSync(fixture)); diff --git a/test/sequential/test-tcp-wrap-connect.js b/test/sequential/test-tcp-wrap-connect.js new file mode 100644 index 000000000..9e915d243 --- /dev/null +++ b/test/sequential/test-tcp-wrap-connect.js @@ -0,0 +1,80 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var TCP = process.binding('tcp_wrap').TCP; +var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; +var ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; + +function makeConnection() { + var client = new TCP(); + + var req = new TCPConnectWrap(); + var err = client.connect(req, '127.0.0.1', common.PORT); + assert.equal(err, 0); + + req.oncomplete = function(status, client_, req_) { + assert.equal(0, status); + assert.equal(client, client_); + assert.equal(req, req_); + + console.log('connected'); + var shutdownReq = new ShutdownWrap(); + var err = client.shutdown(shutdownReq); + assert.equal(err, 0); + + shutdownReq.oncomplete = function(status, client_, req_) { + console.log('shutdown complete'); + assert.equal(0, status); + assert.equal(client, client_); + assert.equal(shutdownReq, req_); + shutdownCount++; + client.close(); + }; + }; +} + +///// + +var connectCount = 0; +var endCount = 0; +var shutdownCount = 0; + +var server = require('net').Server(function(s) { + console.log('got connection'); + connectCount++; + s.resume(); + s.on('end', function() { + console.log('got eof'); + endCount++; + s.destroy(); + server.close(); + }); +}); + +server.listen(common.PORT, makeConnection); + +process.on('exit', function() { + assert.equal(1, shutdownCount); + assert.equal(1, connectCount); + assert.equal(1, endCount); +}); diff --git a/test/sequential/test-tcp-wrap-listen.js b/test/sequential/test-tcp-wrap-listen.js new file mode 100644 index 000000000..5801368ba --- /dev/null +++ b/test/sequential/test-tcp-wrap-listen.js @@ -0,0 +1,123 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +var TCP = process.binding('tcp_wrap').TCP; +var WriteWrap = process.binding('stream_wrap').WriteWrap; + +var server = new TCP(); + +var r = server.bind('0.0.0.0', common.PORT); +assert.equal(0, r); + +server.listen(128); + +var slice, sliceCount = 0, eofCount = 0; + +var writeCount = 0; +var recvCount = 0; + +server.onconnection = function(err, client) { + assert.equal(0, client.writeQueueSize); + console.log('got connection'); + + function maybeCloseClient() { + if (client.pendingWrites.length == 0 && client.gotEOF) { + console.log('close client'); + client.close(); + } + } + + client.readStart(); + client.pendingWrites = []; + client.onread = function(err, buffer) { + if (buffer) { + assert.ok(buffer.length > 0); + + assert.equal(0, client.writeQueueSize); + + var req = new WriteWrap(); + req.async = false; + var err = client.writeBuffer(req, buffer); + assert.equal(err, 0); + client.pendingWrites.push(req); + + console.log('client.writeQueueSize: ' + client.writeQueueSize); + // 11 bytes should flush + assert.equal(0, client.writeQueueSize); + + if (req.async) + req.oncomplete = done; + else + process.nextTick(done.bind(null, 0, client, req)); + + function done(status, client_, req_) { + assert.equal(req, client.pendingWrites.shift()); + + // Check parameters. + assert.equal(0, status); + assert.equal(client, client_); + assert.equal(req, req_); + + console.log('client.writeQueueSize: ' + client.writeQueueSize); + assert.equal(0, client.writeQueueSize); + + writeCount++; + console.log('write ' + writeCount); + maybeCloseClient(); + }; + + sliceCount++; + } else { + console.log('eof'); + client.gotEOF = true; + server.close(); + eofCount++; + maybeCloseClient(); + } + }; +}; + +var net = require('net'); + +var c = net.createConnection(common.PORT); +c.on('connect', function() { + c.end('hello world'); +}); + +c.setEncoding('utf8'); +c.on('data', function(d) { + assert.equal('hello world', d); + recvCount++; +}); + +c.on('close', function() { + console.error('client closed'); +}); + +process.on('exit', function() { + assert.equal(1, sliceCount); + assert.equal(1, eofCount); + assert.equal(1, writeCount); + assert.equal(1, recvCount); +}); diff --git a/test/sequential/test-tls-honorcipherorder.js b/test/sequential/test-tls-honorcipherorder.js new file mode 100644 index 000000000..6b24d7514 --- /dev/null +++ b/test/sequential/test-tls-honorcipherorder.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var tls = require('tls'); +var fs = require('fs'); +var nconns = 0; +// test only in TLSv1 to use DES which is no longer supported TLSv1.2 +// to be safe when the default method is updated in the future +var SSL_Method = 'TLSv1_method'; +var localhost = '127.0.0.1'; + +process.on('exit', function() { + assert.equal(nconns, 6); +}); + +function test(honorCipherOrder, clientCipher, expectedCipher, cb) { + var soptions = { + secureProtocol: SSL_Method, + key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), + cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), + ciphers: 'DES-CBC-SHA:AES256-SHA:RC4-SHA:ECDHE-RSA-AES256-SHA', + honorCipherOrder: !!honorCipherOrder + }; + + var server = tls.createServer(soptions, function(cleartextStream) { + nconns++; + + // End socket to send CLOSE_NOTIFY and TCP FIN packet, otherwise + // it may hang for ~30 seconds in FIN_WAIT_1 state (at least on OSX). + cleartextStream.end(); + }); + server.listen(common.PORT, localhost, function() { + var coptions = { + rejectUnauthorized: false, + secureProtocol: SSL_Method + }; + if (clientCipher) { + coptions.ciphers = clientCipher; + } + var client = tls.connect(common.PORT, localhost, coptions, function() { + var cipher = client.getCipher(); + client.end(); + server.close(); + assert.equal(cipher.name, expectedCipher); + if (cb) cb(); + }); + }); +} + +test1(); + +function test1() { + // Client has the preference of cipher suites by default + test(false, 'AES256-SHA:DES-CBC-SHA:RC4-SHA','AES256-SHA', test2); +} + +function test2() { + // Server has the preference of cipher suites where DES-CBC-SHA is in + // the first. + test(true, 'AES256-SHA:DES-CBC-SHA:RC4-SHA', 'DES-CBC-SHA', test3); +} + +function test3() { + // Server has the preference of cipher suites. RC4-SHA is given + // higher priority over DES-CBC-SHA among client cipher suites. + test(true, 'RC4-SHA:AES256-SHA', 'AES256-SHA', test4); +} + +function test4() { + // As client has only one cipher, server has no choice in regardless + // of honorCipherOrder. + test(true, 'RC4-SHA', 'RC4-SHA', test5); +} + +function test5() { + // Client did not explicitly set ciphers. Ensure that client defaults to + // sane ciphers. Even though server gives top priority to DES-CBC-SHA + // it should not be negotiated because it's not in default client ciphers. + test(true, null, 'AES256-SHA', test6); +} + +function test6() { + // Ensure that `tls.DEFAULT_CIPHERS` is used + SSL_Method = 'TLSv1_2_method'; + tls.DEFAULT_CIPHERS = 'ECDHE-RSA-AES256-SHA'; + test(true, null, 'ECDHE-RSA-AES256-SHA'); +} diff --git a/test/sequential/test-util-debug.js b/test/sequential/test-util-debug.js new file mode 100644 index 000000000..6d9c28a95 --- /dev/null +++ b/test/sequential/test-util-debug.js @@ -0,0 +1,87 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); + +if (process.argv[2] === 'child') + child(); +else + parent(); + +function parent() { + test('foo,tud,bar', true); + test('foo,tud', true); + test('tud,bar', true); + test('tud', true); + test('foo,bar', false); + test('', false); +} + +function test(environ, shouldWrite) { + var expectErr = ''; + if (shouldWrite) { + expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' + + 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; + } + var expectOut = 'ok\n'; + var didTest = false; + + var spawn = require('child_process').spawn; + var child = spawn(process.execPath, [__filename, 'child'], { + env: { NODE_DEBUG: environ } + }); + + expectErr = expectErr.split('%PID%').join(child.pid); + + var err = ''; + child.stderr.setEncoding('utf8'); + child.stderr.on('data', function(c) { + err += c; + }); + + var out = ''; + child.stdout.setEncoding('utf8'); + child.stdout.on('data', function(c) { + out += c; + }); + + child.on('close', function(c) { + assert(!c); + assert.equal(err, expectErr); + assert.equal(out, expectOut); + didTest = true; + console.log('ok %j %j', environ, shouldWrite); + }); + + process.on('exit', function() { + assert(didTest); + }); +} + + +function child() { + var util = require('util'); + var debug = util.debuglog('tud'); + debug('this', { is: 'a' }, /debugging/); + debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); + console.log('ok'); +} diff --git a/test/sequential/test-vm-syntax-error-stderr.js b/test/sequential/test-vm-syntax-error-stderr.js new file mode 100644 index 000000000..3e88e1ff1 --- /dev/null +++ b/test/sequential/test-vm-syntax-error-stderr.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var common = require('../common'); +var assert = require('assert'); +var path = require('path'); +var child_process = require('child_process'); + +var wrong_script = path.join(common.fixturesDir, 'cert.pem'); + +var p = child_process.spawn(process.execPath, [ + '-e', + 'try { require(process.argv[1]); } catch (e) { console.log(e.stack); }', + wrong_script +]); + +p.stderr.on('data', function(data) { + assert(false, 'Unexpected stderr data: ' + data); +}); + +var output = ''; + +p.stdout.on('data', function(data) { + output += data; +}); + +process.on('exit', function() { + assert(/BEGIN CERT/.test(output)); + assert(/^\s+\^/m.test(output)); + assert(/Invalid left-hand side expression in prefix operation/.test(output)); +}); diff --git a/test/sequential/test-vm-timeout-rethrow.js b/test/sequential/test-vm-timeout-rethrow.js new file mode 100644 index 000000000..c2158a135 --- /dev/null +++ b/test/sequential/test-vm-timeout-rethrow.js @@ -0,0 +1,48 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var assert = require('assert'); +var vm = require('vm'); +var spawn = require('child_process').spawn; + +if (process.argv[2] === 'child') { + var code = 'var j = 0;\n' + + 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + 'j;'; + + var ctx = vm.createContext({ + add: function(x, y) { + return x + y; + } + }); + + vm.runInContext(code, ctx, { timeout: 1 }); +} else { + var proc = spawn(process.execPath, process.argv.slice(1).concat('child')); + var err = ''; + proc.stderr.on('data', function(data) { + err += data; + }); + + process.on('exit', function() { + assert.ok(/Script execution timed out/.test(err)); + }); +} diff --git a/test/sequential/test-zerolengthbufferbug.js b/test/sequential/test-zerolengthbufferbug.js new file mode 100644 index 000000000..395e35baf --- /dev/null +++ b/test/sequential/test-zerolengthbufferbug.js @@ -0,0 +1,57 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Serving up a zero-length buffer should work. + +var common = require('../common'); +var assert = require('assert'); +var http = require('http'); + +var server = http.createServer(function(req, res) { + var buffer = new Buffer(0); + // FIXME: WTF gjslint want this? + res.writeHead(200, {'Content-Type': 'text/html', + 'Content-Length': buffer.length}); + res.end(buffer); +}); + +var gotResponse = false; +var resBodySize = 0; + +server.listen(common.PORT, function() { + http.get({ port: common.PORT }, function(res) { + gotResponse = true; + + res.on('data', function(d) { + resBodySize += d.length; + }); + + res.on('end', function(d) { + server.close(); + }); + }); +}); + +process.on('exit', function() { + assert.ok(gotResponse); + assert.equal(0, resBodySize); +}); + diff --git a/test/sequential/testcfg.py b/test/sequential/testcfg.py new file mode 100644 index 000000000..b1fce1810 --- /dev/null +++ b/test/sequential/testcfg.py @@ -0,0 +1,6 @@ +import sys, os +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import testpy + +def GetConfiguration(context, root): + return testpy.SimpleTestConfiguration(context, root, 'sequential') diff --git a/test/simple/net-socket-readystate.js b/test/simple/net-socket-readystate.js deleted file mode 100644 index 107d68e95..000000000 --- a/test/simple/net-socket-readystate.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - -var sock = new net.Socket(); - -var server = net.createServer().listen(common.PORT, function() { - assert(!sock.readable); - assert(!sock.writable); - assert.equal(sock.readyState, 'closed'); - - sock.connect(common.PORT, function() { - assert.equal(sock.readable, true); - assert.equal(sock.writable, true); - assert.equal(sock.readyState, 'open'); - - sock.end(); - assert(!sock.writable); - assert.equal(sock.readyState, 'readOnly'); - - server.close(); - sock.on('close', function() { - assert(!sock.readable); - assert(!sock.writable); - assert.equal(sock.readyState, 'closed'); - }); - }); - - assert.equal(sock.readyState, 'opening'); -}); diff --git a/test/simple/path.js b/test/simple/path.js deleted file mode 100644 index 21c08d3c6..000000000 --- a/test/simple/path.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -// This is actually more a fixture than a test. It is used to make -var common = require('../common'); -// sure that require('./path') and require('path') do different things. -// It has to be in the same directory as the test 'test-module-loading.js' -// and it has to have the same name as an internal module. -exports.path_func = function() { - return 'path_func'; -}; diff --git a/test/simple/simple.status b/test/simple/simple.status deleted file mode 100644 index d310575f1..000000000 --- a/test/simple/simple.status +++ /dev/null @@ -1,4 +0,0 @@ -prefix simple - -[$system==linux] -test-net-GH-5504 : PASS,FLAKY diff --git a/test/simple/test-assert.js b/test/simple/test-assert.js deleted file mode 100644 index 84ea9249c..000000000 --- a/test/simple/test-assert.js +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var a = require('assert'); - -function makeBlock(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function() { - return f.apply(this, args); - }; -} - -assert.ok(common.indirectInstanceOf(a.AssertionError.prototype, Error), - 'a.AssertionError instanceof Error'); - -assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)'); - -assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)'); - -assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')')); - -assert.throws(makeBlock(a.ok, false), - a.AssertionError, 'ok(false)'); - -assert.doesNotThrow(makeBlock(a.ok, true), - a.AssertionError, 'ok(true)'); - -assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')'); - -assert.throws(makeBlock(a.equal, true, false), a.AssertionError, 'equal'); - -assert.doesNotThrow(makeBlock(a.equal, null, null), 'equal'); - -assert.doesNotThrow(makeBlock(a.equal, undefined, undefined), 'equal'); - -assert.doesNotThrow(makeBlock(a.equal, null, undefined), 'equal'); - -assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal'); - -assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal'); - -assert.doesNotThrow(makeBlock(a.notEqual, true, false), 'notEqual'); - -assert.throws(makeBlock(a.notEqual, true, true), - a.AssertionError, 'notEqual'); - -assert.throws(makeBlock(a.strictEqual, 2, '2'), - a.AssertionError, 'strictEqual'); - -assert.throws(makeBlock(a.strictEqual, null, undefined), - a.AssertionError, 'strictEqual'); - -assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'), 'notStrictEqual'); - -// deepEquals joy! -// 7.2 -assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14), - new Date(2000, 3, 14)), 'deepEqual date'); - -assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), - a.AssertionError, - 'deepEqual date'); - -// 7.3 -assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m)); -assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm)); -assert.throws(makeBlock(a.deepEqual, /ab/, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/g, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/i, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/m, /a/)); -assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im)); - -var re1 = /a/; -re1.lastIndex = 3; -assert.throws(makeBlock(a.deepEqual, re1, /a/)); - - -// 7.4 -assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual == check'); -assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual == check'); -assert.throws(makeBlock(a.deepEqual, 4, '5'), - a.AssertionError, - 'deepEqual == check'); - -// 7.5 -// having the same number of owned properties && the same set of keys -assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4}, {a: 4})); -assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'})); -assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4'])); -assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); -//(although not necessarily the same order), -assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); -var a1 = [1, 2, 3]; -var a2 = [1, 2, 3]; -a1.a = 'test'; -a1.b = true; -a2.b = true; -a2.a = 'test'; -assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), - a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); - -// having an identical prototype property -var nbRoot = { - toString: function() { return this.first + ' ' + this.last; } -}; - -function nameBuilder(first, last) { - this.first = first; - this.last = last; - return this; -} -nameBuilder.prototype = nbRoot; - -function nameBuilder2(first, last) { - this.first = first; - this.last = last; - return this; -} -nameBuilder2.prototype = nbRoot; - -var nb1 = new nameBuilder('Ryan', 'Dahl'); -var nb2 = new nameBuilder2('Ryan', 'Dahl'); - -assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); - -nameBuilder2.prototype = Object; -nb2 = new nameBuilder2('Ryan', 'Dahl'); -assert.throws(makeBlock(a.deepEqual, nb1, nb2), a.AssertionError); - -// String literal + object blew up my implementation... -assert.throws(makeBlock(a.deepEqual, 'a', {}), a.AssertionError); - -// Testing the throwing -function thrower(errorConstructor) { - throw new errorConstructor('test'); -} -var aethrow = makeBlock(thrower, a.AssertionError); -aethrow = makeBlock(thrower, a.AssertionError); - -// the basic calls work -assert.throws(makeBlock(thrower, a.AssertionError), - a.AssertionError, 'message'); -assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError); -assert.throws(makeBlock(thrower, a.AssertionError)); - -// if not passing an error, catch all. -assert.throws(makeBlock(thrower, TypeError)); - -// when passing a type, only catch errors of the appropriate type -var threw = false; -try { - a.throws(makeBlock(thrower, TypeError), a.AssertionError); -} catch (e) { - threw = true; - assert.ok(e instanceof TypeError, 'type'); -} -assert.equal(true, threw, - 'a.throws with an explicit error is eating extra errors', - a.AssertionError); -threw = false; - -// doesNotThrow should pass through all errors -try { - a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError); -} catch (e) { - threw = true; - assert.ok(e instanceof TypeError); -} -assert.equal(true, threw, - 'a.doesNotThrow with an explicit error is eating extra errors'); - -// key difference is that throwing our correct error makes an assertion error -try { - a.doesNotThrow(makeBlock(thrower, TypeError), TypeError); -} catch (e) { - threw = true; - assert.ok(e instanceof a.AssertionError); -} -assert.equal(true, threw, - 'a.doesNotThrow is not catching type matching errors'); - -assert.throws(function() {assert.ifError(new Error('test error'))}); -assert.doesNotThrow(function() {assert.ifError(null)}); -assert.doesNotThrow(function() {assert.ifError()}); - -// make sure that validating using constructor really works -threw = false; -try { - assert.throws( - function() { - throw ({}); - }, - Array - ); -} catch (e) { - threw = true; -} -assert.ok(threw, 'wrong constructor validation'); - -// use a RegExp to validate error message -a.throws(makeBlock(thrower, TypeError), /test/); - -// use a fn to validate error object -a.throws(makeBlock(thrower, TypeError), function(err) { - if ((err instanceof TypeError) && /test/.test(err)) { - return true; - } -}); - - -// GH-207. Make sure deepEqual doesn't loop forever on circular refs - -var b = {}; -b.b = b; - -var c = {}; -c.b = c; - -var gotError = false; -try { - assert.deepEqual(b, c); -} catch (e) { - gotError = true; -} - -// GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. -var args = (function() { return arguments; })(); -a.throws(makeBlock(a.deepEqual, [], args)); -a.throws(makeBlock(a.deepEqual, args, [])); - -console.log('All OK'); -assert.ok(gotError); - - -// #217 -function testAssertionMessage(actual, expected) { - try { - assert.equal(actual, ''); - } catch (e) { - assert.equal(e.toString(), - ['AssertionError:', expected, '==', '""'].join(' ')); - assert.ok(e.generatedMessage, "Message not marked as generated"); - } -} -testAssertionMessage(undefined, '"undefined"'); -testAssertionMessage(null, 'null'); -testAssertionMessage(true, 'true'); -testAssertionMessage(false, 'false'); -testAssertionMessage(0, '0'); -testAssertionMessage(100, '100'); -testAssertionMessage(NaN, '"NaN"'); -testAssertionMessage(Infinity, '"Infinity"'); -testAssertionMessage(-Infinity, '"-Infinity"'); -testAssertionMessage('', '""'); -testAssertionMessage('foo', '"foo"'); -testAssertionMessage([], '[]'); -testAssertionMessage([1, 2, 3], '[1,2,3]'); -testAssertionMessage(/a/, '"/a/"'); -testAssertionMessage(/abc/gim, '"/abc/gim"'); -testAssertionMessage(function f() {}, '"function f() {}"'); -testAssertionMessage({}, '{}'); -testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}'); -testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, - '{"a":"NaN","b":"Infinity","c":"-Infinity"}'); - -// #2893 -try { - assert.throws(function () { - assert.ifError(null); - }); -} catch (e) { - threw = true; - assert.equal(e.message, 'Missing expected exception..'); -} -assert.ok(threw); - -// #5292 -try { - assert.equal(1, 2); -} catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2') - assert.ok(e.generatedMessage, 'Message not marked as generated'); -} - -try { - assert.equal(1, 2, 'oh no'); -} catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no') - assert.equal(e.generatedMessage, false, - 'Message incorrectly marked as generated'); -} diff --git a/test/simple/test-bad-unicode.js b/test/simple/test-bad-unicode.js deleted file mode 100644 index 0e57909a6..000000000 --- a/test/simple/test-bad-unicode.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'), - exception = null; - -try { - eval('"\\uc/ef"'); -} catch (e) { - exception = e; -} - -assert(exception instanceof SyntaxError); diff --git a/test/simple/test-beforeexit-event-exit.js b/test/simple/test-beforeexit-event-exit.js deleted file mode 100644 index be6f2c607..000000000 --- a/test/simple/test-beforeexit-event-exit.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); - -process.on('beforeExit', function() { - assert(false, 'exit should not allow this to occur'); -}); - -process.exit(); diff --git a/test/simple/test-beforeexit-event.js b/test/simple/test-beforeexit-event.js deleted file mode 100644 index 41cc1d376..000000000 --- a/test/simple/test-beforeexit-event.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var net = require('net'); -var util = require('util'); -var revivals = 0; -var deaths = 0; - -process.on('beforeExit', function() { deaths++; } ); - -process.once('beforeExit', tryImmediate); - -function tryImmediate() { - console.log('set immediate'); - setImmediate(function() { - revivals++; - process.once('beforeExit', tryTimer); - }); -} - -function tryTimer() { - console.log('set a timeout'); - setTimeout(function () { - console.log('timeout cb, do another once beforeExit'); - revivals++; - process.once('beforeExit', tryListen); - }, 1); -} - -function tryListen() { - console.log('create a server'); - net.createServer() - .listen(0) - .on('listening', function() { - revivals++; - this.close(); - }); -} - -process.on('exit', function() { - assert.equal(4, deaths); - assert.equal(3, revivals); -}); diff --git a/test/simple/test-buffer-ascii.js b/test/simple/test-buffer-ascii.js deleted file mode 100644 index 784597a48..000000000 --- a/test/simple/test-buffer-ascii.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// ASCII conversion in node.js simply masks off the high bits, -// it doesn't do transliteration. -assert.equal(Buffer('hérité').toString('ascii'), 'hC)ritC)'); - -// 71 characters, 78 bytes. The ’ character is a triple-byte sequence. -var input = 'C’est, graphiquement, la réunion d’un accent aigu ' + - 'et d’un accent grave.'; - -var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + - 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' + - 'accent grave.'; - -var buf = Buffer(input); - -for (var i = 0; i < expected.length; ++i) { - assert.equal(buf.slice(i).toString('ascii'), expected.slice(i)); - - // Skip remainder of multi-byte sequence. - if (input.charCodeAt(i) > 65535) ++i; - if (input.charCodeAt(i) > 127) ++i; -} diff --git a/test/simple/test-buffer-concat.js b/test/simple/test-buffer-concat.js deleted file mode 100644 index 858d6924f..000000000 --- a/test/simple/test-buffer-concat.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var zero = []; -var one = [ new Buffer('asdf') ]; -var long = []; -for (var i = 0; i < 10; i++) long.push(new Buffer('asdf')); - -var flatZero = Buffer.concat(zero); -var flatOne = Buffer.concat(one); -var flatLong = Buffer.concat(long); -var flatLongLen = Buffer.concat(long, 40); - -assert(flatZero.length === 0); -assert(flatOne.toString() === 'asdf'); -assert(flatOne === one[0]); -assert(flatLong.toString() === (new Array(10+1).join('asdf'))); -assert(flatLongLen.toString() === (new Array(10+1).join('asdf'))); - -console.log("ok"); diff --git a/test/simple/test-buffer-inspect.js b/test/simple/test-buffer-inspect.js deleted file mode 100644 index a13c69b4e..000000000 --- a/test/simple/test-buffer-inspect.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var util = require('util'); - -var buffer = require('buffer'); - -buffer.INSPECT_MAX_BYTES = 2; - -var b = new Buffer(4); -b.fill('1234'); - -var s = new buffer.SlowBuffer(4); -s.fill('1234'); - -var expected = ''; - -assert.strictEqual(util.inspect(b), expected); -assert.strictEqual(util.inspect(s), expected); - -b = new Buffer(2); -b.fill('12'); - -s = new buffer.SlowBuffer(2); -s.fill('12'); - -expected = ''; - -assert.strictEqual(util.inspect(b), expected); -assert.strictEqual(util.inspect(s), expected); - -buffer.INSPECT_MAX_BYTES = Infinity; - -assert.doesNotThrow(function() { - assert.strictEqual(util.inspect(b), expected); - assert.strictEqual(util.inspect(s), expected); -}); \ No newline at end of file diff --git a/test/simple/test-buffer-slice.js b/test/simple/test-buffer-slice.js deleted file mode 100644 index 1a462bd0b..000000000 --- a/test/simple/test-buffer-slice.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Buffer = require('buffer').Buffer; - -var buff = new Buffer(Buffer.poolSize + 1); -var slicedBuffer = buff.slice(); -assert.equal(slicedBuffer.parent, - buff, - "slicedBufffer should have its parent set to the original " + - " buffer"); diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js deleted file mode 100644 index bf742f934..000000000 --- a/test/simple/test-buffer.js +++ /dev/null @@ -1,1186 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Buffer = require('buffer').Buffer; -var SlowBuffer = require('buffer').SlowBuffer; -var smalloc = require('smalloc'); - -// counter to ensure unique value is always copied -var cntr = 0; - -var b = Buffer(1024); // safe constructor - -console.log('b.length == %d', b.length); -assert.strictEqual(1024, b.length); - -b[0] = -1; -assert.strictEqual(b[0], 255); - -for (var i = 0; i < 1024; i++) { - b[i] = i % 256; -} - -for (var i = 0; i < 1024; i++) { - assert.strictEqual(i % 256, b[i]); -} - -var c = new Buffer(512); -console.log('c.length == %d', c.length); -assert.strictEqual(512, c.length); - -// First check Buffer#fill() works as expected. - -assert.throws(function() { - Buffer(8).fill('a', -1); -}); - -assert.throws(function() { - Buffer(8).fill('a', 0, 9); -}); - -// Make sure this doesn't hang indefinitely. -Buffer(8).fill(''); - -var buf = new Buffer(64); -buf.fill(10); -for (var i = 0; i < buf.length; i++) - assert.equal(buf[i], 10); - -buf.fill(11, 0, buf.length >> 1); -for (var i = 0; i < buf.length >> 1; i++) - assert.equal(buf[i], 11); -for (var i = (buf.length >> 1) + 1; i < buf.length; i++) - assert.equal(buf[i], 10); - -buf.fill('h'); -for (var i = 0; i < buf.length; i++) - assert.equal('h'.charCodeAt(0), buf[i]); - -buf.fill(0); -for (var i = 0; i < buf.length; i++) - assert.equal(0, buf[i]); - -buf.fill(null); -for (var i = 0; i < buf.length; i++) - assert.equal(0, buf[i]); - -buf.fill(1, 16, 32); -for (var i = 0; i < 16; i++) - assert.equal(0, buf[i]); -for (; i < 32; i++) - assert.equal(1, buf[i]); -for (; i < buf.length; i++) - assert.equal(0, buf[i]); - -var buf = new Buffer(10); -buf.fill('abc'); -assert.equal(buf.toString(), 'abcabcabca'); -buf.fill('է'); -assert.equal(buf.toString(), 'էէէէէ'); - -// copy 512 bytes, from 0 to 512. -b.fill(++cntr); -c.fill(++cntr); -var copied = b.copy(c, 0, 0, 512); -console.log('copied %d bytes from b into c', copied); -assert.strictEqual(512, copied); -for (var i = 0; i < c.length; i++) { - assert.strictEqual(b[i], c[i]); -} - -// copy c into b, without specifying sourceEnd -b.fill(++cntr); -c.fill(++cntr); -var copied = c.copy(b, 0, 0); -console.log('copied %d bytes from c into b w/o sourceEnd', copied); -assert.strictEqual(c.length, copied); -for (var i = 0; i < c.length; i++) { - assert.strictEqual(c[i], b[i]); -} - -// copy c into b, without specifying sourceStart -b.fill(++cntr); -c.fill(++cntr); -var copied = c.copy(b, 0); -console.log('copied %d bytes from c into b w/o sourceStart', copied); -assert.strictEqual(c.length, copied); -for (var i = 0; i < c.length; i++) { - assert.strictEqual(c[i], b[i]); -} - -// copy longer buffer b to shorter c without targetStart -b.fill(++cntr); -c.fill(++cntr); -var copied = b.copy(c); -console.log('copied %d bytes from b into c w/o targetStart', copied); -assert.strictEqual(c.length, copied); -for (var i = 0; i < c.length; i++) { - assert.strictEqual(b[i], c[i]); -} - -// copy starting near end of b to c -b.fill(++cntr); -c.fill(++cntr); -var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); -console.log('copied %d bytes from end of b into beginning of c', copied); -assert.strictEqual(Math.floor(c.length / 2), copied); -for (var i = 0; i < Math.floor(c.length / 2); i++) { - assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); -} -for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) { - assert.strictEqual(c[c.length-1], c[i]); -} - -// try to copy 513 bytes, and check we don't overrun c -b.fill(++cntr); -c.fill(++cntr); -var copied = b.copy(c, 0, 0, 513); -console.log('copied %d bytes from b trying to overrun c', copied); -assert.strictEqual(c.length, copied); -for (var i = 0; i < c.length; i++) { - assert.strictEqual(b[i], c[i]); -} - -// copy 768 bytes from b into b -b.fill(++cntr); -b.fill(++cntr, 256); -var copied = b.copy(b, 0, 256, 1024); -console.log('copied %d bytes from b into b', copied); -assert.strictEqual(768, copied); -for (var i = 0; i < b.length; i++) { - assert.strictEqual(cntr, b[i]); -} - -// copy string longer than buffer length (failure will segfault) -var bb = new Buffer(10); -bb.fill('hello crazy world'); - - -var caught_error = null; - -// try to copy from before the beginning of b -caught_error = null; -try { - var copied = b.copy(c, 0, 100, 10); -} catch (err) { - caught_error = err; -} - -// copy throws at negative sourceStart -assert.throws(function() { - Buffer(5).copy(Buffer(5), 0, -1); -}, RangeError); - -// check sourceEnd resets to targetEnd if former is greater than the latter -b.fill(++cntr); -c.fill(++cntr); -var copied = b.copy(c, 0, 0, 1025); -console.log('copied %d bytes from b into c', copied); -for (var i = 0; i < c.length; i++) { - assert.strictEqual(b[i], c[i]); -} - -// throw with negative sourceEnd -console.log('test copy at negative sourceEnd'); -assert.throws(function() { - b.copy(c, 0, 0, -1); -}, RangeError); - -// when sourceStart is greater than sourceEnd, zero copied -assert.equal(b.copy(c, 0, 100, 10), 0); - -// when targetStart > targetLength, zero copied -assert.equal(b.copy(c, 512, 0, 10), 0); - -var caught_error; - -// invalid encoding for Buffer.toString -caught_error = null; -try { - var copied = b.toString('invalid'); -} catch (err) { - caught_error = err; -} -assert.strictEqual('Unknown encoding: invalid', caught_error.message); - -// invalid encoding for Buffer.write -caught_error = null; -try { - var copied = b.write('test string', 0, 5, 'invalid'); -} catch (err) { - caught_error = err; -} -assert.strictEqual('Unknown encoding: invalid', caught_error.message); - -// try to create 0-length buffers -new Buffer(''); -new Buffer('', 'ascii'); -new Buffer('', 'binary'); -new Buffer(0); - -// try to write a 0-length string beyond the end of b -assert.throws(function() { - b.write('', 2048); -}, RangeError); - -// throw when writing to negative offset -assert.throws(function() { - b.write('a', -1); -}, RangeError); - -// throw when writing past bounds from the pool -assert.throws(function() { - b.write('a', 2048); -}, RangeError); - -// throw when writing to negative offset -assert.throws(function() { - b.write('a', -1); -}, RangeError); - -// try to copy 0 bytes worth of data into an empty buffer -b.copy(new Buffer(0), 0, 0, 0); - -// try to copy 0 bytes past the end of the target buffer -b.copy(new Buffer(0), 1, 1, 1); -b.copy(new Buffer(1), 1, 1, 1); - -// try to copy 0 bytes from past the end of the source buffer -b.copy(new Buffer(1), 0, 2048, 2048); - -// try to toString() a 0-length slice of a buffer, both within and without the -// valid buffer range -assert.equal(new Buffer('abc').toString('ascii', 0, 0), ''); -assert.equal(new Buffer('abc').toString('ascii', -100, -100), ''); -assert.equal(new Buffer('abc').toString('ascii', 100, 100), ''); - -// try toString() with a object as a encoding -assert.equal(new Buffer('abc').toString({toString: function() { - return 'ascii'; -}}), 'abc'); - -// testing for smart defaults and ability to pass string values as offset -var writeTest = new Buffer('abcdes'); -writeTest.write('n', 'ascii'); -writeTest.write('o', 'ascii', '1'); -writeTest.write('d', '2', 'ascii'); -writeTest.write('e', 3, 'ascii'); -writeTest.write('j', 'ascii', 4); -assert.equal(writeTest.toString(), 'nodejs'); - -var asciiString = 'hello world'; -var offset = 100; -for (var j = 0; j < 500; j++) { - - for (var i = 0; i < asciiString.length; i++) { - b[i] = asciiString.charCodeAt(i); - } - var asciiSlice = b.toString('ascii', 0, asciiString.length); - assert.equal(asciiString, asciiSlice); - - var written = b.write(asciiString, offset, 'ascii'); - assert.equal(asciiString.length, written); - var asciiSlice = b.toString('ascii', offset, offset + asciiString.length); - assert.equal(asciiString, asciiSlice); - - var sliceA = b.slice(offset, offset + asciiString.length); - var sliceB = b.slice(offset, offset + asciiString.length); - for (var i = 0; i < asciiString.length; i++) { - assert.equal(sliceA[i], sliceB[i]); - } - - // TODO utf8 slice tests -} - - -for (var j = 0; j < 100; j++) { - var slice = b.slice(100, 150); - assert.equal(50, slice.length); - for (var i = 0; i < 50; i++) { - assert.equal(b[100 + i], slice[i]); - } -} - - -// make sure only top level parent propagates from allocPool -var b = new Buffer(5); -var c = b.slice(0, 4); -var d = c.slice(0, 2); -assert.equal(b.parent, c.parent); -assert.equal(b.parent, d.parent); - -// also from a non-pooled instance -var b = new SlowBuffer(5); -var c = b.slice(0, 4); -var d = c.slice(0, 2); -assert.equal(b, c.parent); -assert.equal(b, d.parent); - - - -// Bug regression test -var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 -var buffer = new Buffer(32); -var size = buffer.write(testValue, 0, 'utf8'); -console.log('bytes written to buffer: ' + size); -var slice = buffer.toString('utf8', 0, size); -assert.equal(slice, testValue); - - -// Test triple slice -var a = new Buffer(8); -for (var i = 0; i < 8; i++) a[i] = i; -var b = a.slice(4, 8); -assert.equal(4, b[0]); -assert.equal(5, b[1]); -assert.equal(6, b[2]); -assert.equal(7, b[3]); -var c = b.slice(2, 4); -assert.equal(6, c[0]); -assert.equal(7, c[1]); - - -var d = new Buffer([23, 42, 255]); -assert.equal(d.length, 3); -assert.equal(d[0], 23); -assert.equal(d[1], 42); -assert.equal(d[2], 255); -assert.deepEqual(d, new Buffer(d)); - -var e = new Buffer('über'); -console.error('uber: \'%s\'', e.toString()); -assert.deepEqual(e, new Buffer([195, 188, 98, 101, 114])); - -var f = new Buffer('über', 'ascii'); -console.error('f.length: %d (should be 4)', f.length); -assert.deepEqual(f, new Buffer([252, 98, 101, 114])); - -['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { - var f = new Buffer('über', encoding); - console.error('f.length: %d (should be 8)', f.length); - assert.deepEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0])); - - var f = new Buffer('привет', encoding); - console.error('f.length: %d (should be 12)', f.length); - assert.deepEqual(f, new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4])); - assert.equal(f.toString(encoding), 'привет'); - - var f = new Buffer([0, 0, 0, 0, 0]); - assert.equal(f.length, 5); - var size = f.write('あいうえお', encoding); - console.error('bytes written to buffer: %d (should be 4)', size); - assert.equal(size, 4); - assert.deepEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00])); -}); - -var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D) -assert.equal(f.length, 4); -assert.deepEqual(f, new Buffer('3DD84DDC', 'hex')); - - -var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; -var g = new Buffer(arrayIsh); -assert.deepEqual(g, new Buffer([0, 1, 2, 3])); -var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; -g = new Buffer(strArrayIsh); -assert.deepEqual(g, new Buffer([0, 1, 2, 3])); - - -// -// Test toString('base64') -// -assert.equal('TWFu', (new Buffer('Man')).toString('base64')); - -// test that regular and URL-safe base64 both work -var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff]; -assert.deepEqual(Buffer('//++/++/++//', 'base64'), Buffer(expected)); -assert.deepEqual(Buffer('__--_--_--__', 'base64'), Buffer(expected)); - -// big example -var quote = 'Man is distinguished, not only by his reason, but by this ' + - 'singular passion from other animals, which is a lust ' + - 'of the mind, that by a perseverance of delight in the continued ' + - 'and indefatigable generation of knowledge, exceeds the short ' + - 'vehemence of any carnal pleasure.'; -var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24s' + - 'IGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltY' + - 'WxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZX' + - 'JzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmR' + - 'lZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo' + - 'ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='; -assert.equal(expected, (new Buffer(quote)).toString('base64')); - - -b = new Buffer(1024); -var bytesWritten = b.write(expected, 0, 'base64'); -assert.equal(quote.length, bytesWritten); -assert.equal(quote, b.toString('ascii', 0, quote.length)); - -// check that the base64 decoder ignores whitespace -var expectedWhite = expected.slice(0, 60) + ' \n' + - expected.slice(60, 120) + ' \n' + - expected.slice(120, 180) + ' \n' + - expected.slice(180, 240) + ' \n' + - expected.slice(240, 300) + '\n' + - expected.slice(300, 360) + '\n'; -b = new Buffer(1024); -bytesWritten = b.write(expectedWhite, 0, 'base64'); -assert.equal(quote.length, bytesWritten); -assert.equal(quote, b.toString('ascii', 0, quote.length)); - -// check that the base64 decoder on the constructor works -// even in the presence of whitespace. -b = new Buffer(expectedWhite, 'base64'); -assert.equal(quote.length, b.length); -assert.equal(quote, b.toString('ascii', 0, quote.length)); - -// check that the base64 decoder ignores illegal chars -var expectedIllegal = expected.slice(0, 60) + ' \x80' + - expected.slice(60, 120) + ' \xff' + - expected.slice(120, 180) + ' \x00' + - expected.slice(180, 240) + ' \x98' + - expected.slice(240, 300) + '\x03' + - expected.slice(300, 360); -b = new Buffer(expectedIllegal, 'base64'); -assert.equal(quote.length, b.length); -assert.equal(quote, b.toString('ascii', 0, quote.length)); - - -assert.equal(new Buffer('', 'base64').toString(), ''); -assert.equal(new Buffer('K', 'base64').toString(), ''); - -// multiple-of-4 with padding -assert.equal(new Buffer('Kg==', 'base64').toString(), '*'); -assert.equal(new Buffer('Kio=', 'base64').toString(), '**'); -assert.equal(new Buffer('Kioq', 'base64').toString(), '***'); -assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****'); -assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****'); -assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******'); -assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******'); -assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********'); -assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********'); -assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(), - '**********'); -assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(), - '***********'); -assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(), - '************'); -assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(), - '*************'); -assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(), - '**************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(), - '***************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(), - '****************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(), - '*****************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(), - '******************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(), - '*******************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(), - '********************'); - -// no padding, not a multiple of 4 -assert.equal(new Buffer('Kg', 'base64').toString(), '*'); -assert.equal(new Buffer('Kio', 'base64').toString(), '**'); -assert.equal(new Buffer('KioqKg', 'base64').toString(), '****'); -assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****'); -assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******'); -assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********'); -assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********'); -assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********'); -assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(), - '*************'); -assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(), - '**************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(), - '****************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(), - '*****************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(), - '*******************'); -assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(), - '********************'); - -// handle padding graciously, multiple-of-4 or not -assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', - 'base64').length, 32); -assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', - 'base64').length, 32); -assert.equal(new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', - 'base64').length, 32); -assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', - 'base64').length, 31); -assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', - 'base64').length, 31); -assert.equal(new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', - 'base64').length, 31); - -// This string encodes single '.' character in UTF-16 -var dot = new Buffer('//4uAA==', 'base64'); -assert.equal(dot[0], 0xff); -assert.equal(dot[1], 0xfe); -assert.equal(dot[2], 0x2e); -assert.equal(dot[3], 0x00); -assert.equal(dot.toString('base64'), '//4uAA=='); - -// Writing base64 at a position > 0 should not mangle the result. -// -// https://github.com/joyent/node/issues/402 -var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh']; -var buf = new Buffer(64); -var pos = 0; - -for (var i = 0; i < segments.length; ++i) { - pos += b.write(segments[i], pos, 'base64'); -} -assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!'); - -// Creating buffers larger than pool size. -var l = Buffer.poolSize + 5; -var s = ''; -for (i = 0; i < l; i++) { - s += 'h'; -} - -var b = new Buffer(s); - -for (i = 0; i < l; i++) { - assert.equal('h'.charCodeAt(0), b[i]); -} - -var sb = b.toString(); -assert.equal(sb.length, s.length); -assert.equal(sb, s); - - -// Single argument slice -b = new Buffer('abcde'); -assert.equal('bcde', b.slice(1).toString()); - -// byte length -assert.equal(14, Buffer.byteLength('Il était tué')); -assert.equal(14, Buffer.byteLength('Il était tué', 'utf8')); -['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { - assert.equal(24, Buffer.byteLength('Il était tué', encoding)); -}); -assert.equal(12, Buffer.byteLength('Il était tué', 'ascii')); -assert.equal(12, Buffer.byteLength('Il était tué', 'binary')); - -// slice(0,0).length === 0 -assert.equal(0, Buffer('hello').slice(0, 0).length); - -// test hex toString -console.log('Create hex string from buffer'); -var hexb = new Buffer(256); -for (var i = 0; i < 256; i++) { - hexb[i] = i; -} -var hexStr = hexb.toString('hex'); -assert.equal(hexStr, - '000102030405060708090a0b0c0d0e0f' + - '101112131415161718191a1b1c1d1e1f' + - '202122232425262728292a2b2c2d2e2f' + - '303132333435363738393a3b3c3d3e3f' + - '404142434445464748494a4b4c4d4e4f' + - '505152535455565758595a5b5c5d5e5f' + - '606162636465666768696a6b6c6d6e6f' + - '707172737475767778797a7b7c7d7e7f' + - '808182838485868788898a8b8c8d8e8f' + - '909192939495969798999a9b9c9d9e9f' + - 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' + - 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' + - 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' + - 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' + - 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' + - 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'); - -console.log('Create buffer from hex string'); -var hexb2 = new Buffer(hexStr, 'hex'); -for (var i = 0; i < 256; i++) { - assert.equal(hexb2[i], hexb[i]); -} - -// test an invalid slice end. -console.log('Try to slice off the end of the buffer'); -var b = new Buffer([1, 2, 3, 4, 5]); -var b2 = b.toString('hex', 1, 10000); -var b3 = b.toString('hex', 1, 5); -var b4 = b.toString('hex', 1); -assert.equal(b2, b3); -assert.equal(b2, b4); - - -function buildBuffer(data) { - if (Array.isArray(data)) { - var buffer = new Buffer(data.length); - data.forEach(function(v, k) { - buffer[k] = v; - }); - return buffer; - } - return null; -} - -var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]); - -console.log(x.inspect()); -assert.equal('', x.inspect()); - -var z = x.slice(4); -console.log(z.inspect()); -console.log(z.length); -assert.equal(5, z.length); -assert.equal(0x6f, z[0]); -assert.equal(0xa3, z[1]); -assert.equal(0x62, z[2]); -assert.equal(0x61, z[3]); -assert.equal(0x72, z[4]); - -var z = x.slice(0); -console.log(z.inspect()); -console.log(z.length); -assert.equal(z.length, x.length); - -var z = x.slice(0, 4); -console.log(z.inspect()); -console.log(z.length); -assert.equal(4, z.length); -assert.equal(0x81, z[0]); -assert.equal(0xa3, z[1]); - -var z = x.slice(0, 9); -console.log(z.inspect()); -console.log(z.length); -assert.equal(9, z.length); - -var z = x.slice(1, 4); -console.log(z.inspect()); -console.log(z.length); -assert.equal(3, z.length); -assert.equal(0xa3, z[0]); - -var z = x.slice(2, 4); -console.log(z.inspect()); -console.log(z.length); -assert.equal(2, z.length); -assert.equal(0x66, z[0]); -assert.equal(0x6f, z[1]); - -assert.equal(0, Buffer('hello').slice(0, 0).length); - -['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { - var b = new Buffer(10); - b.write('あいうえお', encoding); - assert.equal(b.toString(encoding), 'あいうえお'); -}); - -// Binary encoding should write only one byte per character. -var b = Buffer([0xde, 0xad, 0xbe, 0xef]); -var s = String.fromCharCode(0xffff); -b.write(s, 0, 'binary'); -assert.equal(0xff, b[0]); -assert.equal(0xad, b[1]); -assert.equal(0xbe, b[2]); -assert.equal(0xef, b[3]); -s = String.fromCharCode(0xaaee); -b.write(s, 0, 'binary'); -assert.equal(0xee, b[0]); -assert.equal(0xad, b[1]); -assert.equal(0xbe, b[2]); -assert.equal(0xef, b[3]); - -// #1210 Test UTF-8 string includes null character -var buf = new Buffer('\0'); -assert.equal(buf.length, 1); -buf = new Buffer('\0\0'); -assert.equal(buf.length, 2); - -buf = new Buffer(2); -var written = buf.write(''); // 0byte -assert.equal(written, 0); -written = buf.write('\0'); // 1byte (v8 adds null terminator) -assert.equal(written, 1); -written = buf.write('a\0'); // 1byte * 2 -assert.equal(written, 2); -written = buf.write('あ'); // 3bytes -assert.equal(written, 0); -written = buf.write('\0あ'); // 1byte + 3bytes -assert.equal(written, 1); -written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes -assert.equal(written, 2); - -buf = new Buffer(10); -written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) -assert.equal(written, 9); -written = buf.write('あいう\0'); // 3bytes * 3 + 1byte -assert.equal(written, 10); - -// #243 Test write() with maxLength -var buf = new Buffer(4); -buf.fill(0xFF); -var written = buf.write('abcd', 1, 2, 'utf8'); -console.log(buf); -assert.equal(written, 2); -assert.equal(buf[0], 0xFF); -assert.equal(buf[1], 0x61); -assert.equal(buf[2], 0x62); -assert.equal(buf[3], 0xFF); - -buf.fill(0xFF); -written = buf.write('abcd', 1, 4); -console.log(buf); -assert.equal(written, 3); -assert.equal(buf[0], 0xFF); -assert.equal(buf[1], 0x61); -assert.equal(buf[2], 0x62); -assert.equal(buf[3], 0x63); - -buf.fill(0xFF); -written = buf.write('abcd', 'utf8', 1, 2); // legacy style -console.log(buf); -assert.equal(written, 2); -assert.equal(buf[0], 0xFF); -assert.equal(buf[1], 0x61); -assert.equal(buf[2], 0x62); -assert.equal(buf[3], 0xFF); - -buf.fill(0xFF); -written = buf.write('abcdef', 1, 2, 'hex'); -console.log(buf); -assert.equal(written, 2); -assert.equal(buf[0], 0xFF); -assert.equal(buf[1], 0xAB); -assert.equal(buf[2], 0xCD); -assert.equal(buf[3], 0xFF); - -['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { - buf.fill(0xFF); - written = buf.write('abcd', 0, 2, encoding); - console.log(buf); - assert.equal(written, 2); - assert.equal(buf[0], 0x61); - assert.equal(buf[1], 0x00); - assert.equal(buf[2], 0xFF); - assert.equal(buf[3], 0xFF); -}); - -// test offset returns are correct -var b = new Buffer(16); -assert.equal(4, b.writeUInt32LE(0, 0)); -assert.equal(6, b.writeUInt16LE(0, 4)); -assert.equal(7, b.writeUInt8(0, 6)); -assert.equal(8, b.writeInt8(0, 7)); -assert.equal(16, b.writeDoubleLE(0, 8)); - -// test unmatched surrogates not producing invalid utf8 output -// ef bf bd = utf-8 representation of unicode replacement character -// see https://codereview.chromium.org/121173009/ -buf = new Buffer('ab\ud800cd', 'utf8'); -assert.equal(buf[0], 0x61); -assert.equal(buf[1], 0x62); -assert.equal(buf[2], 0xef); -assert.equal(buf[3], 0xbf); -assert.equal(buf[4], 0xbd); -assert.equal(buf[5], 0x63); -assert.equal(buf[6], 0x64); - -// test for buffer overrun -buf = new Buffer([0, 0, 0, 0, 0]); // length: 5 -var sub = buf.slice(0, 4); // length: 4 -written = sub.write('12345', 'binary'); -assert.equal(written, 4); -assert.equal(buf[4], 0); - -// Check for fractional length args, junk length args, etc. -// https://github.com/joyent/node/issues/1758 -Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec -assert.equal(Buffer(-1).length, 0); -assert.equal(Buffer(NaN).length, 0); -assert.equal(Buffer(3.3).length, 3); -assert.equal(Buffer({length: 3.3}).length, 3); -assert.equal(Buffer({length: 'BAM'}).length, 0); - -// Make sure that strings are not coerced to numbers. -assert.equal(Buffer('99').length, 2); -assert.equal(Buffer('13.37').length, 5); - -// Ensure that the length argument is respected. -'ascii utf8 hex base64 binary'.split(' ').forEach(function(enc) { - assert.equal(Buffer(1).write('aaaaaa', 0, 1, enc), 1); -}); - -// Regression test, guard against buffer overrun in the base64 decoder. -var a = Buffer(3); -var b = Buffer('xxx'); -a.write('aaaaaaaa', 'base64'); -assert.equal(b.toString(), 'xxx'); - -// issue GH-3416 -Buffer(Buffer(0), 0, 0); - -[ 'hex', - 'utf8', - 'utf-8', - 'ascii', - 'binary', - 'base64', - 'ucs2', - 'ucs-2', - 'utf16le', - 'utf-16le' ].forEach(function(enc) { - assert.equal(Buffer.isEncoding(enc), true); - }); - -[ 'utf9', - 'utf-7', - 'Unicode-FTW', - 'new gnu gun' ].forEach(function(enc) { - assert.equal(Buffer.isEncoding(enc), false); - }); - - -// GH-5110 -(function () { - var buffer = new Buffer('test'), - string = JSON.stringify(buffer); - - assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); - - assert.deepEqual(buffer, JSON.parse(string, function(key, value) { - return value && value.type === 'Buffer' - ? new Buffer(value.data) - : value; - })); -})(); - -// issue GH-7849 -(function() { - var buf = new Buffer('test'); - var json = JSON.stringify(buf); - var obj = JSON.parse(json); - var copy = new Buffer(obj); - - assert(buf.equals(copy)); -})(); - -// issue GH-4331 -assert.throws(function() { - new Buffer(0xFFFFFFFF); -}, RangeError); -assert.throws(function() { - new Buffer(0xFFFFFFFFF); -}, RangeError); - - -// attempt to overflow buffers, similar to previous bug in array buffers -assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(0xffffffff); -}, RangeError); - -assert.throws(function() { - var buf = new Buffer(8); - buf.writeFloatLE(0.0, 0xffffffff); -}, RangeError); - -assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(0xffffffff); -}, RangeError); - -assert.throws(function() { - var buf = new Buffer(8); - buf.writeFloatLE(0.0, 0xffffffff); -}, RangeError); - - -// ensure negative values can't get past offset -assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(-1); -}, RangeError); - -assert.throws(function() { - var buf = new Buffer(8); - buf.writeFloatLE(0.0, -1); -}, RangeError); - -assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(-1); -}, RangeError); - -assert.throws(function() { - var buf = new Buffer(8); - buf.writeFloatLE(0.0, -1); -}, RangeError); - -// offset checks -var buf = new Buffer(0); - -assert.throws(function() { buf.readUInt8(0); }, RangeError); -assert.throws(function() { buf.readInt8(0); }, RangeError); - -var buf = new Buffer([0xFF]); - -assert.equal(buf.readUInt8(0), 255); -assert.equal(buf.readInt8(0), -1); - -[16, 32].forEach(function(bits) { - var buf = new Buffer(bits / 8 - 1); - - assert.throws(function() { buf['readUInt' + bits + 'BE'](0); }, - RangeError, - 'readUInt' + bits + 'BE'); - - assert.throws(function() { buf['readUInt' + bits + 'LE'](0); }, - RangeError, - 'readUInt' + bits + 'LE'); - - assert.throws(function() { buf['readInt' + bits + 'BE'](0); }, - RangeError, - 'readInt' + bits + 'BE()'); - - assert.throws(function() { buf['readInt' + bits + 'LE'](0); }, - RangeError, - 'readInt' + bits + 'LE()'); -}); - -[16, 32].forEach(function(bits) { - var buf = new Buffer([0xFF, 0xFF, 0xFF, 0xFF]); - - assert.equal(buf['readUInt' + bits + 'BE'](0), - (0xFFFFFFFF >>> (32 - bits))); - - assert.equal(buf['readUInt' + bits + 'LE'](0), - (0xFFFFFFFF >>> (32 - bits))); - - assert.equal(buf['readInt' + bits + 'BE'](0), - (0xFFFFFFFF >> (32 - bits))); - - assert.equal(buf['readInt' + bits + 'LE'](0), - (0xFFFFFFFF >> (32 - bits))); -}); - -// test for common read(U)IntLE/BE -(function() { - var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); - - assert.equal(buf.readUIntLE(0, 1), 0x01); - assert.equal(buf.readUIntBE(0, 1), 0x01); - assert.equal(buf.readUIntLE(0, 3), 0x030201); - assert.equal(buf.readUIntBE(0, 3), 0x010203); - assert.equal(buf.readUIntLE(0, 5), 0x0504030201); - assert.equal(buf.readUIntBE(0, 5), 0x0102030405); - assert.equal(buf.readUIntLE(0, 6), 0x060504030201); - assert.equal(buf.readUIntBE(0, 6), 0x010203040506); - assert.equal(buf.readIntLE(0, 1), 0x01); - assert.equal(buf.readIntBE(0, 1), 0x01); - assert.equal(buf.readIntLE(0, 3), 0x030201); - assert.equal(buf.readIntBE(0, 3), 0x010203); - assert.equal(buf.readIntLE(0, 5), 0x0504030201); - assert.equal(buf.readIntBE(0, 5), 0x0102030405); - assert.equal(buf.readIntLE(0, 6), 0x060504030201); - assert.equal(buf.readIntBE(0, 6), 0x010203040506); -})(); - -// test for common write(U)IntLE/BE -(function() { - var buf = new Buffer(3); - buf.writeUIntLE(0x123456, 0, 3); - assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); - assert.equal(buf.readUIntLE(0, 3), 0x123456); - - buf = new Buffer(3); - buf.writeUIntBE(0x123456, 0, 3); - assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); - assert.equal(buf.readUIntBE(0, 3), 0x123456); - - buf = new Buffer(3); - buf.writeIntLE(0x123456, 0, 3); - assert.deepEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); - assert.equal(buf.readIntLE(0, 3), 0x123456); - - buf = new Buffer(3); - buf.writeIntBE(0x123456, 0, 3); - assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56]); - assert.equal(buf.readIntBE(0, 3), 0x123456); - - buf = new Buffer(3); - buf.writeIntLE(-0x123456, 0, 3); - assert.deepEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]); - assert.equal(buf.readIntLE(0, 3), -0x123456); - - buf = new Buffer(3); - buf.writeIntBE(-0x123456, 0, 3); - assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]); - assert.equal(buf.readIntBE(0, 3), -0x123456); - - buf = new Buffer(5); - buf.writeUIntLE(0x1234567890, 0, 5); - assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); - assert.equal(buf.readUIntLE(0, 5), 0x1234567890); - - buf = new Buffer(5); - buf.writeUIntBE(0x1234567890, 0, 5); - assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); - assert.equal(buf.readUIntBE(0, 5), 0x1234567890); - - buf = new Buffer(5); - buf.writeIntLE(0x1234567890, 0, 5); - assert.deepEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]); - assert.equal(buf.readIntLE(0, 5), 0x1234567890); - - buf = new Buffer(5); - buf.writeIntBE(0x1234567890, 0, 5); - assert.deepEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]); - assert.equal(buf.readIntBE(0, 5), 0x1234567890); - - buf = new Buffer(5); - buf.writeIntLE(-0x1234567890, 0, 5); - assert.deepEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]); - assert.equal(buf.readIntLE(0, 5), -0x1234567890); - - buf = new Buffer(5); - buf.writeIntBE(-0x1234567890, 0, 5); - assert.deepEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]); - assert.equal(buf.readIntBE(0, 5), -0x1234567890); -})(); - -// test Buffer slice -(function() { - var buf = new Buffer('0123456789'); - assert.equal(buf.slice(-10, 10), '0123456789'); - assert.equal(buf.slice(-20, 10), '0123456789'); - assert.equal(buf.slice(-20, -10), ''); - assert.equal(buf.slice(0, -1), '012345678'); - assert.equal(buf.slice(2, -2), '234567'); - assert.equal(buf.slice(0, 65536), '0123456789'); - assert.equal(buf.slice(65536, 0), ''); - for (var i = 0, s = buf.toString(); i < buf.length; ++i) { - assert.equal(buf.slice(-i), s.slice(-i)); - assert.equal(buf.slice(0, -i), s.slice(0, -i)); - } - // try to slice a zero length Buffer - // see https://github.com/joyent/node/issues/5881 - SlowBuffer(0).slice(0, 1); - // make sure a zero length slice doesn't set the .parent attribute - assert.equal(Buffer(5).slice(0,0).parent, undefined); - // and make sure a proper slice does have a parent - assert.ok(typeof Buffer(5).slice(0, 5).parent === 'object'); -})(); - -// Make sure byteLength properly checks for base64 padding -assert.equal(Buffer.byteLength('aaa=', 'base64'), 2); -assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3); - -// Regression test for #5482: should throw but not assert in C++ land. -assert.throws(function() { - Buffer('', 'buffer'); -}, TypeError); - -// Regression test for #6111. Constructing a buffer from another buffer -// should a) work, and b) not corrupt the source buffer. -(function() { - var a = [0]; - for (var i = 0; i < 7; ++i) a = a.concat(a); - a = a.map(function(_, i) { return i }); - var b = Buffer(a); - var c = Buffer(b); - assert.equal(b.length, a.length); - assert.equal(c.length, a.length); - for (var i = 0, k = a.length; i < k; ++i) { - assert.equal(a[i], i); - assert.equal(b[i], i); - assert.equal(c[i], i); - } -})(); - - -assert.throws(function () { - new Buffer(smalloc.kMaxLength + 1); -}, RangeError); - -assert.throws(function () { - new SlowBuffer(smalloc.kMaxLength + 1); -}, RangeError); - -// Test truncation after decode -var crypto = require('crypto'); - -var b1 = new Buffer('YW55=======', 'base64'); -var b2 = new Buffer('YW55', 'base64'); - -assert.equal( - crypto.createHash('sha1').update(b1).digest('hex'), - crypto.createHash('sha1').update(b2).digest('hex') -); - -// Test Compare -var b = new Buffer(1).fill('a'); -var c = new Buffer(1).fill('c'); -var d = new Buffer(2).fill('aa'); - -assert.equal(b.compare(c), -1); -assert.equal(c.compare(d), 1); -assert.equal(d.compare(b), 1); -assert.equal(b.compare(d), -1); - -assert.equal(Buffer.compare(b, c), -1); -assert.equal(Buffer.compare(c, d), 1); -assert.equal(Buffer.compare(d, b), 1); -assert.equal(Buffer.compare(b, d), -1); - -assert.throws(function() { - var b = new Buffer(1); - Buffer.compare(b, 'abc'); -}); - -assert.throws(function() { - var b = new Buffer(1); - Buffer.compare('abc', b); -}); - -assert.throws(function() { - var b = new Buffer(1); - b.compare('abc'); -}); - -// Test Equals -var b = new Buffer(5).fill('abcdf'); -var c = new Buffer(5).fill('abcdf'); -var d = new Buffer(5).fill('abcde'); -var e = new Buffer(6).fill('abcdef'); - -assert.ok(b.equals(c)); -assert.ok(!c.equals(d)); -assert.ok(!d.equals(e)); - -assert.throws(function() { - var b = new Buffer(1); - b.equals('abc'); -}); diff --git a/test/simple/test-c-ares.js b/test/simple/test-c-ares.js deleted file mode 100644 index 3a3a9223d..000000000 --- a/test/simple/test-c-ares.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var dns = require('dns'); - - -// Try resolution without callback - -dns.lookup(null, function(error, result, addressType) { - assert.equal(null, result); - assert.equal(4, addressType); -}); - -dns.lookup('127.0.0.1', function(error, result, addressType) { - assert.equal('127.0.0.1', result); - assert.equal(4, addressType); -}); - -dns.lookup('::1', function(error, result, addressType) { - assert.equal('::1', result); - assert.equal(6, addressType); -}); - -// Try calling resolve with an unsupported type. -assert.throws(function() { - dns.resolve('www.google.com', 'HI'); -}, /Unknown type/); - -// Windows doesn't usually have an entry for localhost 127.0.0.1 in -// C:\Windows\System32\drivers\etc\hosts -// so we disable this test on Windows. -if (process.platform != 'win32') { - dns.resolve('127.0.0.1', 'PTR', function(error, domains) { - if (error) throw error; - assert.ok(Array.isArray(domains)); - }); -} diff --git a/test/simple/test-chdir.js b/test/simple/test-chdir.js deleted file mode 100644 index 7454bee2d..000000000 --- a/test/simple/test-chdir.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); - -assert.equal(true, process.cwd() !== __dirname); - -process.chdir(__dirname); -assert.equal(true, process.cwd() === __dirname); - -var dir = path.resolve(common.fixturesDir, - 'weird \uc3a4\uc3ab\uc3af characters \u00e1\u00e2\u00e3'); -fs.mkdirSync(dir); -process.chdir(dir); -assert(process.cwd() == dir); - -process.chdir('..'); -assert(process.cwd() == path.resolve(common.fixturesDir)); -fs.rmdirSync(dir); diff --git a/test/simple/test-child-process-buffering.js b/test/simple/test-child-process-buffering.js deleted file mode 100644 index 3fb13b620..000000000 --- a/test/simple/test-child-process-buffering.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; - -var pwd_called = false; -var childClosed = false; -var childExited = false; - -function pwd(callback) { - var output = ''; - var child = common.spawnPwd(); - - child.stdout.setEncoding('utf8'); - child.stdout.on('data', function(s) { - console.log('stdout: ' + JSON.stringify(s)); - output += s; - }); - - child.on('exit', function(c) { - console.log('exit: ' + c); - assert.equal(0, c); - childExited = true; - }); - - child.on('close', function () { - callback(output); - pwd_called = true; - childClosed = true; - }); -} - - -pwd(function(result) { - console.dir(result); - assert.equal(true, result.length > 1); - assert.equal('\n', result[result.length - 1]); -}); - -process.on('exit', function() { - assert.equal(true, pwd_called); - assert.equal(true, childExited); - assert.equal(true, childClosed); -}); diff --git a/test/simple/test-child-process-cwd.js b/test/simple/test-child-process-cwd.js deleted file mode 100644 index b06e8e479..000000000 --- a/test/simple/test-child-process-cwd.js +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var path = require('path'); - -var returns = 0; - -/* - Spawns 'pwd' with given options, then test - - whether the exit code equals forCode, - - optionally whether the stdout result matches forData - (after removing traling whitespace) -*/ -function testCwd(options, forCode, forData) { - var data = ''; - - var child = common.spawnPwd(options); - - child.stdout.setEncoding('utf8'); - - child.stdout.on('data', function(chunk) { - data += chunk; - }); - - child.on('exit', function(code, signal) { - assert.strictEqual(forCode, code); - }); - - child.on('close', function () { - forData && assert.strictEqual(forData, data.replace(/[\s\r\n]+$/, '')); - returns--; - }); - - returns++; - - return child; -} - -// Assume these exist, and 'pwd' gives us the right directory back -if (process.platform == 'win32') { - testCwd({cwd: process.env.windir}, 0, process.env.windir); - testCwd({cwd: 'c:\\'}, 0, 'c:\\'); -} else { - testCwd({cwd: '/dev'}, 0, '/dev'); - testCwd({cwd: '/'}, 0, '/'); -} - -// Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT -(function() { - var errors = 0; - - testCwd({cwd: 'does-not-exist'}, -1).on('error', function(e) { - assert.equal(e.code, 'ENOENT'); - errors++; - }); - - process.on('exit', function() { - assert.equal(errors, 1); - }); -})(); - -// Spawn() shouldn't try to chdir() so this should just work -testCwd(undefined, 0); -testCwd({}, 0); -testCwd({cwd: ''}, 0); -testCwd({cwd: undefined}, 0); -testCwd({cwd: null}, 0); - -// Check whether all tests actually returned -assert.notEqual(0, returns); -process.on('exit', function() { - assert.equal(0, returns); -}); diff --git a/test/simple/test-child-process-default-options.js b/test/simple/test-child-process-default-options.js deleted file mode 100644 index 57ff60441..000000000 --- a/test/simple/test-child-process-default-options.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; - -var isWindows = process.platform === 'win32'; - -process.env.HELLO = 'WORLD'; - -if (isWindows) { - var child = spawn('cmd.exe', ['/c', 'set'], {}); -} else { - var child = spawn('/usr/bin/env', [], {}); -} - -var response = ''; - -child.stdout.setEncoding('utf8'); - -child.stdout.on('data', function(chunk) { - console.log('stdout: ' + chunk); - response += chunk; -}); - -process.on('exit', function() { - assert.ok(response.indexOf('HELLO=WORLD') >= 0, - 'spawn did not use process.env as default'); -}); diff --git a/test/simple/test-child-process-detached.js b/test/simple/test-child-process-detached.js deleted file mode 100644 index 10ce5d152..000000000 --- a/test/simple/test-child-process-detached.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); - -var spawn = require('child_process').spawn; -var childPath = path.join(__dirname, '..', 'fixtures', 'parent-process-nonpersistent.js'); -var persistentPid = -1; - -var child = spawn(process.execPath, [ childPath ]); - -child.stdout.on('data', function (data) { - persistentPid = parseInt(data, 10); -}); - -process.on('exit', function () { - assert(persistentPid !== -1); - assert.throws(function () { - process.kill(child.pid); - }); - assert.doesNotThrow(function () { - process.kill(persistentPid); - }); -}); - diff --git a/test/simple/test-child-process-disconnect.js b/test/simple/test-child-process-disconnect.js deleted file mode 100644 index 5902be8f1..000000000 --- a/test/simple/test-child-process-disconnect.js +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); -var fork = require('child_process').fork; -var net = require('net'); - -// child -if (process.argv[2] === 'child') { - - // Check that the 'disconnect' event is deferred to the next event loop tick. - var disconnect = process.disconnect; - process.disconnect = function() { - disconnect.apply(this, arguments); - // If the event is emitted synchronously, we're too late by now. - process.once('disconnect', common.mustCall(disconnectIsNotAsync)); - // The funky function name makes it show up legible in mustCall errors. - function disconnectIsNotAsync() {} - }; - - var server = net.createServer(); - - server.on('connection', function(socket) { - - socket.resume(); - - process.on('disconnect', function() { - socket.end((process.connected).toString()); - }); - - // when the socket is closed, we will close the server - // allowing the process to self terminate - socket.on('end', function() { - server.close(); - }); - - socket.write('ready'); - }); - - // when the server is ready tell parent - server.on('listening', function() { - process.send('ready'); - }); - - server.listen(common.PORT); - -} else { - // testcase - var child = fork(process.argv[1], ['child']); - - var childFlag = false; - var childSelfTerminate = false; - var parentEmit = false; - var parentFlag = false; - - // when calling .disconnect the event should emit - // and the disconnected flag should be true. - child.on('disconnect', function() { - parentEmit = true; - parentFlag = child.connected; - }); - - // the process should also self terminate without using signals - child.on('exit', function() { - childSelfTerminate = true; - }); - - // when child is listening - child.on('message', function(msg) { - if (msg === 'ready') { - - // connect to child using TCP to know if disconnect was emitted - var socket = net.connect(common.PORT); - - socket.on('data', function(data) { - data = data.toString(); - - // ready to be disconnected - if (data === 'ready') { - child.disconnect(); - assert.throws(child.disconnect.bind(child), Error); - return; - } - - // disconnect is emitted - childFlag = (data === 'true'); - }); - - } - }); - - process.on('exit', function() { - assert.equal(childFlag, false); - assert.equal(parentFlag, false); - - assert.ok(childSelfTerminate); - assert.ok(parentEmit); - }); -} diff --git a/test/simple/test-child-process-double-pipe.js b/test/simple/test-child-process-double-pipe.js deleted file mode 100644 index c09dfa885..000000000 --- a/test/simple/test-child-process-double-pipe.js +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var is_windows = process.platform === 'win32'; - -var common = require('../common'); -var assert = require('assert'), - os = require('os'), - util = require('util'), - spawn = require('child_process').spawn; - -// We're trying to reproduce: -// $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ - -var grep, sed, echo; - -if (is_windows) { - grep = spawn('grep', ['--binary', 'o']), - sed = spawn('sed', ['--binary', 's/o/O/']), - echo = spawn('cmd.exe', - ['/c', 'echo', 'hello&&', 'echo', - 'node&&', 'echo', 'and&&', 'echo', 'world']); -} else { - grep = spawn('grep', ['o']), - sed = spawn('sed', ['s/o/O/']), - echo = spawn('echo', ['hello\nnode\nand\nworld\n']); -} - -/* - * grep and sed hang if the spawn function leaks file descriptors to child - * processes. - * This happens when calling pipe(2) and then forgetting to set the - * FD_CLOEXEC flag on the resulting file descriptors. - * - * This test checks child processes exit, meaning they don't hang like - * explained above. - */ - - - -// pipe echo | grep -echo.stdout.on('data', function(data) { - console.error('grep stdin write ' + data.length); - if (!grep.stdin.write(data)) { - echo.stdout.pause(); - } -}); - -grep.stdin.on('drain', function(data) { - echo.stdout.resume(); -}); - -// propagate end from echo to grep -echo.stdout.on('end', function(code) { - grep.stdin.end(); -}); - -echo.on('exit', function() { - console.error('echo exit'); -}); - -grep.on('exit', function() { - console.error('grep exit'); -}); - -sed.on('exit', function() { - console.error('sed exit'); -}); - - - -// pipe grep | sed -grep.stdout.on('data', function(data) { - console.error('grep stdout ' + data.length); - if (!sed.stdin.write(data)) { - grep.stdout.pause(); - } -}); - -sed.stdin.on('drain', function(data) { - grep.stdout.resume(); -}); - -// propagate end from grep to sed -grep.stdout.on('end', function(code) { - console.error('grep stdout end'); - sed.stdin.end(); -}); - - - -var result = ''; - -// print sed's output -sed.stdout.on('data', function(data) { - result += data.toString('utf8', 0, data.length); - util.print(data); -}); - -sed.stdout.on('end', function(code) { - assert.equal(result, 'hellO' + os.EOL + 'nOde' + os.EOL +'wOrld' + os.EOL); -}); diff --git a/test/simple/test-child-process-emfile.js b/test/simple/test-child-process-emfile.js deleted file mode 100644 index 323bbb0a3..000000000 --- a/test/simple/test-child-process-emfile.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var fs = require('fs'); - -if (process.platform === 'win32') { - console.log('Skipping test, no RLIMIT_NOFILE on Windows.'); - return; -} - -for (;;) { - try { - fs.openSync(__filename, 'r'); - } catch (err) { - assert(err.code === 'EMFILE' || err.code === 'ENFILE'); - break; - } -} - -// Should emit an error, not throw. -var proc = spawn(process.execPath, ['-e', '0']); - -proc.on('error', common.mustCall(function(err) { - assert(err.code === 'EMFILE' || err.code === 'ENFILE'); -})); - -// 'exit' should not be emitted, the process was never spawned. -proc.on('exit', assert.fail); diff --git a/test/simple/test-child-process-env.js b/test/simple/test-child-process-env.js deleted file mode 100644 index caeb1936c..000000000 --- a/test/simple/test-child-process-env.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; - -var isWindows = process.platform === 'win32'; - -var env = { - 'HELLO': 'WORLD' -}; -env.__proto__ = { - 'FOO': 'BAR' -}; - -if (isWindows) { - var child = spawn('cmd.exe', ['/c', 'set'], {env: env}); -} else { - var child = spawn('/usr/bin/env', [], {env: env}); -} - - -var response = ''; - -child.stdout.setEncoding('utf8'); - -child.stdout.on('data', function(chunk) { - console.log('stdout: ' + chunk); - response += chunk; -}); - -process.on('exit', function() { - assert.ok(response.indexOf('HELLO=WORLD') >= 0); - assert.ok(response.indexOf('FOO=BAR') >= 0); -}); diff --git a/test/simple/test-child-process-exec-buffer.js b/test/simple/test-child-process-exec-buffer.js deleted file mode 100644 index 937dce76e..000000000 --- a/test/simple/test-child-process-exec-buffer.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; -var os = require('os'); - -var success_count = 0; - -var str = 'hello'; - -// default encoding -var child = exec("echo " + str, function(err, stdout, stderr) { - assert.ok('string', typeof(stdout), 'Expected stdout to be a string'); - assert.ok('string', typeof(stderr), 'Expected stderr to be a string'); - assert.equal(str + os.EOL, stdout); - - success_count++; -}); - -// no encoding (Buffers expected) -var child = exec("echo " + str, { - encoding: null -}, function(err, stdout, stderr) { - assert.ok(stdout instanceof Buffer, 'Expected stdout to be a Buffer'); - assert.ok(stderr instanceof Buffer, 'Expected stderr to be a Buffer'); - assert.equal(str + os.EOL, stdout.toString()); - - success_count++; -}); - -process.on('exit', function() { - assert.equal(2, success_count); -}); diff --git a/test/simple/test-child-process-exec-cwd.js b/test/simple/test-child-process-exec-cwd.js deleted file mode 100644 index 282faec8b..000000000 --- a/test/simple/test-child-process-exec-cwd.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; - -var success_count = 0; -var error_count = 0; - -var pwdcommand, dir; - -if (process.platform == 'win32') { - pwdcommand = 'echo %cd%'; - dir = 'c:\\windows'; -} else { - pwdcommand = 'pwd'; - dir = '/dev'; -} - -var child = exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { - if (err) { - error_count++; - console.log('error!: ' + err.code); - console.log('stdout: ' + JSON.stringify(stdout)); - console.log('stderr: ' + JSON.stringify(stderr)); - assert.equal(false, err.killed); - } else { - success_count++; - console.log(stdout); - assert.ok(stdout.indexOf(dir) == 0); - } -}); - -process.on('exit', function() { - assert.equal(1, success_count); - assert.equal(0, error_count); -}); diff --git a/test/simple/test-child-process-exec-env.js b/test/simple/test-child-process-exec-env.js deleted file mode 100644 index b14ce741f..000000000 --- a/test/simple/test-child-process-exec-env.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; -var success_count = 0; -var error_count = 0; -var response = ''; -var child; - -function after(err, stdout, stderr) { - if (err) { - error_count++; - console.log('error!: ' + err.code); - console.log('stdout: ' + JSON.stringify(stdout)); - console.log('stderr: ' + JSON.stringify(stderr)); - assert.equal(false, err.killed); - } else { - success_count++; - assert.equal(true, stdout != ''); - } -} - -if (process.platform !== 'win32') { - child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after); -} else { - child = exec('set', { env: { 'HELLO': 'WORLD' } }, after); -} - -child.stdout.setEncoding('utf8'); -child.stdout.on('data', function(chunk) { - response += chunk; -}); - -process.on('exit', function() { - console.log('response: ', response); - assert.equal(1, success_count); - assert.equal(0, error_count); - assert.ok(response.indexOf('HELLO=WORLD') >= 0); -}); diff --git a/test/simple/test-child-process-exec-error.js b/test/simple/test-child-process-exec-error.js deleted file mode 100644 index afe199764..000000000 --- a/test/simple/test-child-process-exec-error.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var child_process = require('child_process'); - -function test(fun, code) { - var errors = 0; - - fun('does-not-exist', function(err) { - assert.equal(err.code, code); - assert(/does\-not\-exist/.test(err.cmd)); - errors++; - }); - - process.on('exit', function() { - assert.equal(errors, 1); - }); -} - -if (process.platform === 'win32') { - test(child_process.exec, 1); // exit code of cmd.exe -} else { - test(child_process.exec, 127); // exit code of /bin/sh -} - -test(child_process.execFile, 'ENOENT'); diff --git a/test/simple/test-child-process-execsync.js b/test/simple/test-child-process-execsync.js deleted file mode 100644 index e97de721f..000000000 --- a/test/simple/test-child-process-execsync.js +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var os = require('os'); - -var execSync = require('child_process').execSync; -var execFileSync = require('child_process').execFileSync; - -var TIMER = 200; -var SLEEP = 2000; - -var start = Date.now(); -var err; -var caught = false; -try -{ - var cmd = util.format('%s -e "setTimeout(function(){}, %d);"', - process.execPath, SLEEP); - var ret = execSync(cmd, {timeout: TIMER}); -} catch (e) { - caught = true; - assert.strictEqual(e.errno, 'ETIMEDOUT'); - err = e; -} finally { - assert.strictEqual(ret, undefined, 'we should not have a return value'); - assert.strictEqual(caught, true, 'execSync should throw'); - var end = Date.now() - start; - assert(end < SLEEP); - assert(err.status > 128 || err.signal); -} - -assert.throws(function() { - execSync('iamabadcommand'); -}, /Command failed: iamabadcommand/); - -var msg = 'foobar'; -var msgBuf = new Buffer(msg + '\n'); - -// console.log ends every line with just '\n', even on Windows. -cmd = util.format('%s -e "console.log(\'%s\');"', process.execPath, msg); - -var ret = execSync(cmd); - -assert.strictEqual(ret.length, msgBuf.length); -assert.deepEqual(ret, msgBuf, 'execSync result buffer should match'); - -ret = execSync(cmd, { encoding: 'utf8' }); - -assert.strictEqual(ret, msg + '\n', 'execSync encoding result should match'); - -var args = [ - '-e', - util.format('console.log("%s");', msg) -]; -ret = execFileSync(process.execPath, args); - -assert.deepEqual(ret, msgBuf); - -ret = execFileSync(process.execPath, args, { encoding: 'utf8' }); - -assert.strictEqual(ret, msg + '\n', 'execFileSync encoding result should match'); - -// Verify that the cwd option works - GH #7824 -(function() { - var response; - var cwd; - - if (process.platform === 'win32') { - cwd = 'c:\\'; - response = execSync('echo %cd%', {cwd: cwd}); - } else { - cwd = '/'; - response = execSync('pwd', {cwd: cwd}); - } - - assert.strictEqual(response.toString().trim(), cwd); -})(); - -// Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 -(function() { - assert.throws(function() { - execSync('exit -1', {stdio: 'ignore'}); - }, /Command failed: exit -1/); -})(); diff --git a/test/simple/test-child-process-exit-code.js b/test/simple/test-child-process-exit-code.js deleted file mode 100644 index c0c25858b..000000000 --- a/test/simple/test-child-process-exit-code.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var path = require('path'); - -var exits = 0; - -var exitScript = path.join(common.fixturesDir, 'exit.js'); -var exitChild = spawn(process.argv[0], [exitScript, 23]); -exitChild.on('exit', function(code, signal) { - assert.strictEqual(code, 23); - assert.strictEqual(signal, null); - - exits++; -}); - - - -var errorScript = path.join(common.fixturesDir, - 'child_process_should_emit_error.js'); -var errorChild = spawn(process.argv[0], [errorScript]); -errorChild.on('exit', function(code, signal) { - assert.ok(code !== 0); - assert.strictEqual(signal, null); - - exits++; -}); - - -process.on('exit', function() { - assert.equal(2, exits); -}); diff --git a/test/simple/test-child-process-fork-and-spawn.js b/test/simple/test-child-process-fork-and-spawn.js deleted file mode 100644 index 989bf7ee3..000000000 --- a/test/simple/test-child-process-fork-and-spawn.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var fork = require('child_process').fork; - -// Fork, then spawn. The spawned process should not hang. -switch (process.argv[2] || '') { -case '': - fork(__filename, ['fork']).on('exit', checkExit); - process.on('exit', haveExit); - break; -case 'fork': - spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); - process.on('exit', haveExit); - break; -case 'spawn': - break; -default: - assert(0); -} - -var seenExit = false; - -function checkExit(statusCode) { - seenExit = true; - assert.equal(statusCode, 0); - process.nextTick(process.exit); -} - -function haveExit() { - assert.equal(seenExit, true); -} diff --git a/test/simple/test-child-process-fork-close.js b/test/simple/test-child-process-fork-close.js deleted file mode 100644 index 342cffec3..000000000 --- a/test/simple/test-child-process-fork-close.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'), - common = require('../common'), - fork = require('child_process').fork, - fork = require('child_process').fork; - -var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); - -var gotMessage = false, - gotExit = false, - gotClose = false; - -cp.on('message', function(message) { - assert(!gotMessage); - assert(!gotClose); - assert.strictEqual(message, 'hello'); - gotMessage = true; -}); - -cp.on('exit', function() { - assert(!gotExit); - assert(!gotClose); - gotExit = true; -}); - -cp.on('close', function() { - assert(gotMessage); - assert(gotExit); - assert(!gotClose); - gotClose = true; -}); - -process.on('exit', function() { - assert(gotMessage); - assert(gotExit); - assert(gotClose); -}); diff --git a/test/simple/test-child-process-fork-dgram.js b/test/simple/test-child-process-fork-dgram.js deleted file mode 100644 index 1c4e9acc3..000000000 --- a/test/simple/test-child-process-fork-dgram.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * The purpose of this test is to make sure that when forking a process, - * sending a fd representing a UDP socket to the child and sending messages - * to this endpoint, these messages are distributed to the parent and the - * child process. - * - * Because it's not really possible to predict how the messages will be - * distributed among the parent and the child processes, we keep sending - * messages until both the parent and the child received at least one - * message. The worst case scenario is when either one never receives - * a message. In this case the test runner will timeout after 60 secs - * and the test will fail. - */ - -var dgram = require('dgram'); -var fork = require('child_process').fork; -var assert = require('assert'); -var common = require('../common'); - -if (process.platform === 'win32') { - console.error('Sending dgram sockets to child processes not supported'); - process.exit(0); -} - -if (process.argv[2] === 'child') { - var childCollected = 0; - var server; - - process.on('message', function removeMe(msg, clusterServer) { - if (msg === 'server') { - server = clusterServer; - - server.on('message', function () { - process.send('gotMessage'); - }); - - } else if (msg === 'stop') { - server.close(); - process.removeListener('message', removeMe); - } - }); - -} else { - var server = dgram.createSocket('udp4'); - var client = dgram.createSocket('udp4'); - var child = fork(__filename, ['child']); - - var msg = new Buffer('Some bytes'); - - var childGotMessage = false; - var parentGotMessage = false; - - server.on('message', function (msg, rinfo) { - parentGotMessage = true; - }); - - server.on('listening', function () { - child.send('server', server); - - child.once('message', function (msg) { - if (msg === 'gotMessage') { - childGotMessage = true; - } - }); - - sendMessages(); - }); - - var sendMessages = function () { - var timer = setInterval(function () { - client.send(msg, 0, msg.length, common.PORT, '127.0.0.1', function(err) { - if (err) throw err; - } - ); - - /* - * Both the parent and the child got at least one message, - * test passed, clean up everyting. - */ - if (parentGotMessage && childGotMessage) { - clearInterval(timer); - shutdown(); - } - - }, 1); - }; - - var shutdown = function () { - child.send('stop'); - - server.close(); - client.close(); - }; - - server.bind(common.PORT, '127.0.0.1'); - - process.once('exit', function () { - assert(parentGotMessage); - assert(childGotMessage); - }); -} diff --git a/test/simple/test-child-process-fork-exec-argv.js b/test/simple/test-child-process-fork-exec-argv.js deleted file mode 100644 index d0da341c2..000000000 --- a/test/simple/test-child-process-fork-exec-argv.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var child_process = require('child_process'); -var spawn = child_process.spawn; -var fork = child_process.fork; - -if (process.argv[2] === 'fork') { - process.stdout.write(JSON.stringify(process.execArgv), function() { - process.exit(); - }); -} else if (process.argv[2] === 'child') { - fork(__filename, ['fork']); -} else { - var execArgv = ['--harmony_proxies', '--stack-size=256']; - var args = [__filename, 'child', 'arg0']; - - var child = spawn(process.execPath, execArgv.concat(args)); - var out = ''; - - child.stdout.on('data', function (chunk) { - out += chunk; - }); - - child.on('exit', function () { - assert.deepEqual(JSON.parse(out), execArgv); - }); -} diff --git a/test/simple/test-child-process-fork-exec-path.js b/test/simple/test-child-process-fork-exec-path.js deleted file mode 100755 index e0cf77c28..000000000 --- a/test/simple/test-child-process-fork-exec-path.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var cp = require('child_process'); -var fs = require('fs'); -var path = require('path'); -var common = require('../common'); -var msg = {test: 'this'}; -var nodePath = process.execPath; -var copyPath = path.join(common.tmpDir, 'node-copy.exe'); - -if (process.env.FORK) { - assert(process.send); - assert.equal(process.argv[0], copyPath); - process.send(msg); - process.exit(); -} -else { - try { - fs.unlinkSync(copyPath); - } - catch (e) { - if (e.code !== 'ENOENT') throw e; - } - fs.writeFileSync(copyPath, fs.readFileSync(nodePath)); - fs.chmodSync(copyPath, '0755'); - - // slow but simple - var envCopy = JSON.parse(JSON.stringify(process.env)); - envCopy.FORK = 'true'; - var child = require('child_process').fork(__filename, { - execPath: copyPath, - env: envCopy - }); - child.on('message', common.mustCall(function(recv) { - assert.deepEqual(msg, recv); - })); - child.on('exit', common.mustCall(function(code) { - fs.unlinkSync(copyPath); - assert.equal(code, 0); - })); -} diff --git a/test/simple/test-child-process-fork-getconnections.js b/test/simple/test-child-process-fork-getconnections.js deleted file mode 100644 index f8fed6884..000000000 --- a/test/simple/test-child-process-fork-getconnections.js +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); -var fork = require('child_process').fork; -var net = require('net'); -var count = 12; - -if (process.argv[2] === 'child') { - var sockets = []; - var id = process.argv[3]; - - process.on('message', function(m, socket) { - if (m.cmd === 'new') { - assert(socket); - assert(socket instanceof net.Socket, 'should be a net.Socket'); - sockets.push(socket); - socket.on('end', function() { - if (!this.closingOnPurpose) - throw new Error('[c] closing by accident!'); - }); - } - - if (m.cmd === 'close') { - assert.equal(socket, undefined); - sockets[m.id].once('close', function() { - process.send({ id: m.id, status: 'closed' }); - }); - sockets[m.id].destroy(); - } - }); - -} else { - var child = fork(process.argv[1], ['child']); - - child.on('exit', function(code, signal) { - if (!childKilled) - throw new Error('child died unexpectedly!'); - }); - - var server = net.createServer(); - var sockets = []; - var sent = 0; - - server.on('connection', function(socket) { - child.send({ cmd: 'new' }, socket, { track: false }); - sockets.push(socket); - - if (sockets.length === count) { - closeSockets(0); - } - }); - - var disconnected = 0; - var clients = []; - server.on('listening', function() { - var j = count, client; - while (j--) { - client = net.connect(common.PORT, '127.0.0.1'); - client.id = j; - client.on('close', function() { - disconnected += 1; - }); - clients.push(client); - } - }); - - var childKilled = false; - function closeSockets(i) { - if (i === count) { - childKilled = true; - server.close(); - child.kill(); - return; - } - - sent++; - child.send({ id: i, cmd: 'close' }); - child.once('message', function(m) { - assert(m.status === 'closed'); - server.getConnections(function(err, num) { - closeSockets(i + 1); - }); - }); - }; - - var closeEmitted = false; - server.on('close', function() { - closeEmitted = true; - }); - - server.listen(common.PORT, '127.0.0.1'); - - process.on('exit', function() { - assert.equal(sent, count); - assert.equal(disconnected, count); - assert.ok(closeEmitted); - console.log('ok'); - }); -} diff --git a/test/simple/test-child-process-fork-net.js b/test/simple/test-child-process-fork-net.js deleted file mode 100644 index feb2588fe..000000000 --- a/test/simple/test-child-process-fork-net.js +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); -var fork = require('child_process').fork; -var net = require('net'); - -// progress tracker -function ProgressTracker(missing, callback) { - this.missing = missing; - this.callback = callback; -} -ProgressTracker.prototype.done = function() { - this.missing -= 1; - this.check(); -}; -ProgressTracker.prototype.check = function() { - if (this.missing === 0) this.callback(); -}; - -if (process.argv[2] === 'child') { - - var serverScope; - - process.on('message', function onServer(msg, server) { - if (msg.what !== 'server') return; - process.removeListener('message', onServer); - - serverScope = server; - - server.on('connection', function(socket) { - console.log('CHILD: got connection'); - process.send({what: 'connection'}); - socket.destroy(); - }); - - // start making connection from parent - console.log('CHILD: server listening'); - process.send({what: 'listening'}); - }); - - process.on('message', function onClose(msg) { - if (msg.what !== 'close') return; - process.removeListener('message', onClose); - - serverScope.on('close', function() { - process.send({what: 'close'}); - }); - serverScope.close(); - }); - - process.on('message', function onSocket(msg, socket) { - if (msg.what !== 'socket') return; - process.removeListener('message', onSocket); - socket.end('echo'); - console.log('CHILD: got socket'); - }); - - process.send({what: 'ready'}); -} else { - - var child = fork(process.argv[1], ['child']); - - child.on('exit', function() { - console.log('CHILD: died'); - }); - - // send net.Server to child and test by connecting - var testServer = function(callback) { - - // destroy server execute callback when done - var progress = new ProgressTracker(2, function() { - server.on('close', function() { - console.log('PARENT: server closed'); - child.send({what: 'close'}); - }); - server.close(); - }); - - // we expect 10 connections and close events - var connections = new ProgressTracker(10, progress.done.bind(progress)); - var closed = new ProgressTracker(10, progress.done.bind(progress)); - - // create server and send it to child - var server = net.createServer(); - server.on('connection', function(socket) { - console.log('PARENT: got connection'); - socket.destroy(); - connections.done(); - }); - server.on('listening', function() { - console.log('PARENT: server listening'); - child.send({what: 'server'}, server); - }); - server.listen(common.PORT); - - // handle client messages - var messageHandlers = function(msg) { - - if (msg.what === 'listening') { - // make connections - var socket; - for (var i = 0; i < 10; i++) { - socket = net.connect(common.PORT, function() { - console.log('CLIENT: connected'); - }); - socket.on('close', function() { - closed.done(); - console.log('CLIENT: closed'); - }); - } - - } else if (msg.what === 'connection') { - // child got connection - connections.done(); - } else if (msg.what === 'close') { - child.removeListener('message', messageHandlers); - callback(); - } - }; - - child.on('message', messageHandlers); - }; - - // send net.Socket to child - var testSocket = function(callback) { - - // create a new server and connect to it, - // but the socket will be handled by the child - var server = net.createServer(); - server.on('connection', function(socket) { - socket.on('close', function() { - console.log('CLIENT: socket closed'); - }); - child.send({what: 'socket'}, socket); - }); - server.on('close', function() { - console.log('PARENT: server closed'); - callback(); - }); - // don't listen on the same port, because SmartOS sometimes says - // that the server's fd is closed, but it still cannot listen - // on the same port again. - // - // An isolated test for this would be lovely, but for now, this - // will have to do. - server.listen(common.PORT + 1, function() { - console.error('testSocket, listening'); - var connect = net.connect(common.PORT + 1); - var store = ''; - connect.on('data', function(chunk) { - store += chunk; - console.log('CLIENT: got data'); - }); - connect.on('close', function() { - console.log('CLIENT: closed'); - assert.equal(store, 'echo'); - server.close(); - }); - }); - }; - - // create server and send it to child - var serverSuccess = false; - var socketSuccess = false; - child.on('message', function onReady(msg) { - if (msg.what !== 'ready') return; - child.removeListener('message', onReady); - - testServer(function() { - serverSuccess = true; - - testSocket(function() { - socketSuccess = true; - child.kill(); - }); - }); - - }); - - process.on('exit', function() { - assert.ok(serverSuccess); - assert.ok(socketSuccess); - }); - -} diff --git a/test/simple/test-child-process-fork-net2.js b/test/simple/test-child-process-fork-net2.js deleted file mode 100644 index 098870d48..000000000 --- a/test/simple/test-child-process-fork-net2.js +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); -var fork = require('child_process').fork; -var net = require('net'); -var count = 12; - -if (process.argv[2] === 'child') { - var needEnd = []; - var id = process.argv[3]; - - process.on('message', function(m, socket) { - if (!socket) return; - - console.error('[%d] got socket', id, m); - - // will call .end('end') or .write('write'); - socket[m](m); - - socket.resume(); - - socket.on('data', function() { - console.error('[%d] socket.data', id, m); - }); - - socket.on('end', function() { - console.error('[%d] socket.end', id, m); - }); - - // store the unfinished socket - if (m === 'write') { - needEnd.push(socket); - } - - socket.on('close', function(had_error) { - console.error('[%d] socket.close', id, had_error, m); - }); - - socket.on('finish', function() { - console.error('[%d] socket finished', id, m); - }); - }); - - process.on('message', function(m) { - if (m !== 'close') return; - console.error('[%d] got close message', id); - needEnd.forEach(function(endMe, i) { - console.error('[%d] ending %d/%d', id, i, needEnd.length); - endMe.end('end'); - }); - }); - - process.on('disconnect', function() { - console.error('[%d] process disconnect, ending', id); - needEnd.forEach(function(endMe, i) { - console.error('[%d] ending %d/%d', id, i, needEnd.length); - endMe.end('end'); - }); - }); - -} else { - - var child1 = fork(process.argv[1], ['child', '1']); - var child2 = fork(process.argv[1], ['child', '2']); - var child3 = fork(process.argv[1], ['child', '3']); - - var server = net.createServer(); - - var connected = 0, - closed = 0; - server.on('connection', function(socket) { - switch (connected % 6) { - case 0: - child1.send('end', socket, { track: false }); break; - case 1: - child1.send('write', socket, { track: true }); break; - case 2: - child2.send('end', socket, { track: true }); break; - case 3: - child2.send('write', socket, { track: false }); break; - case 4: - child3.send('end', socket, { track: false }); break; - case 5: - child3.send('write', socket, { track: false }); break; - } - connected += 1; - - socket.once('close', function() { - console.log('[m] socket closed, total %d', ++closed); - }); - - if (connected === count) { - closeServer(); - } - }); - - var disconnected = 0; - server.on('listening', function() { - - var j = count, client; - while (j--) { - client = net.connect(common.PORT, '127.0.0.1'); - client.on('error', function() { - // This can happen if we kill the child too early. - // The client should still get a close event afterwards. - console.error('[m] CLIENT: error event'); - }); - client.on('close', function() { - console.error('[m] CLIENT: close event'); - disconnected += 1; - }); - // XXX This resume() should be unnecessary. - // a stream high water mark should be enough to keep - // consuming the input. - client.resume(); - } - }); - - var closeEmitted = false; - server.on('close', function() { - console.error('[m] server close'); - closeEmitted = true; - - console.error('[m] killing child processes'); - child1.kill(); - child2.kill(); - child3.kill(); - }); - - server.listen(common.PORT, '127.0.0.1'); - - var timeElasped = 0; - var closeServer = function() { - console.error('[m] closeServer'); - var startTime = Date.now(); - server.on('close', function() { - console.error('[m] emit(close)'); - timeElasped = Date.now() - startTime; - }); - - console.error('[m] calling server.close'); - server.close(); - - setTimeout(function() { - assert(!closeEmitted); - console.error('[m] sending close to children'); - child1.send('close'); - child2.send('close'); - child3.disconnect(); - }, 200); - }; - - process.on('exit', function() { - assert.equal(disconnected, count); - assert.equal(connected, count); - assert.ok(closeEmitted); - assert.ok(timeElasped >= 190 && timeElasped <= 1000, - 'timeElasped was not between 190 and 1000 ms'); - }); -} diff --git a/test/simple/test-child-process-fork-ref.js b/test/simple/test-child-process-fork-ref.js deleted file mode 100644 index 21954ec73..000000000 --- a/test/simple/test-child-process-fork-ref.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; - -if (process.argv[2] === 'child') { - process.send('1'); - - // check that child don't instantly die - setTimeout(function() { - process.send('2'); - }, 200); - - process.on('disconnect', function () { - process.stdout.write('3'); - }); - -} else { - var child = fork(__filename, ['child'], {silent: true}); - - var ipc = [], stdout = ''; - - child.on('message', function (msg) { - ipc.push(msg); - - if (msg === '2') child.disconnect(); - }); - - child.stdout.on('data', function (chunk) { - stdout += chunk; - }); - - child.once('exit', function () { - assert.deepEqual(ipc, ['1', '2']); - assert.equal(stdout, '3'); - }); -} diff --git a/test/simple/test-child-process-fork-ref2.js b/test/simple/test-child-process-fork-ref2.js deleted file mode 100644 index 3d604142b..000000000 --- a/test/simple/test-child-process-fork-ref2.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; - -if (process.argv[2] === 'child') { - console.log('child -> call disconnect'); - process.disconnect(); - - setTimeout(function() { - console.log('child -> will this keep it alive?'); - process.on('message', function () { }); - }, 400); - -} else { - var child = fork(__filename, ['child']); - - child.on('disconnect', function () { - console.log('parent -> disconnect'); - }); - - child.once('exit', function () { - console.log('parent -> exit'); - }); -} diff --git a/test/simple/test-child-process-fork.js b/test/simple/test-child-process-fork.js deleted file mode 100644 index 41cc28c72..000000000 --- a/test/simple/test-child-process-fork.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); -var fork = require('child_process').fork; -var args = ['foo', 'bar']; - -var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); -assert.deepEqual(args, ['foo', 'bar']); - -var messageCount = 0; - -n.on('message', function(m) { - console.log('PARENT got message:', m); - assert.ok(m.foo); - messageCount++; -}); - -// https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) -// returns "undefined" but JSON.parse() cannot parse that... -assert.throws(function() { n.send(undefined); }, TypeError); -assert.throws(function() { n.send(); }, TypeError); - -n.send({ hello: 'world' }); - -var childExitCode = -1; -n.on('exit', function(c) { - childExitCode = c; -}); - -process.on('exit', function() { - assert.ok(childExitCode == 0); -}); diff --git a/test/simple/test-child-process-fork3.js b/test/simple/test-child-process-fork3.js deleted file mode 100644 index 0f75b029e..000000000 --- a/test/simple/test-child-process-fork3.js +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var child_process = require('child_process'); - -child_process.fork(common.fixturesDir + '/empty.js'); // should not hang diff --git a/test/simple/test-child-process-internal.js b/test/simple/test-child-process-internal.js deleted file mode 100644 index dd7ce556b..000000000 --- a/test/simple/test-child-process-internal.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -//messages -var PREFIX = 'NODE_'; -var normal = {cmd: 'foo' + PREFIX}; -var internal = {cmd: PREFIX + 'bar'}; - -if (process.argv[2] === 'child') { - //send non-internal message containing PREFIX at a non prefix position - process.send(normal); - - //send inernal message - process.send(internal); - - process.exit(0); - -} else { - - var fork = require('child_process').fork; - var child = fork(process.argv[1], ['child']); - - var gotNormal; - child.once('message', function(data) { - gotNormal = data; - }); - - var gotInternal; - child.once('internalMessage', function(data) { - gotInternal = data; - }); - - process.on('exit', function() { - assert.deepEqual(gotNormal, normal); - assert.deepEqual(gotInternal, internal); - }); -} diff --git a/test/simple/test-child-process-ipc.js b/test/simple/test-child-process-ipc.js deleted file mode 100644 index e8144e439..000000000 --- a/test/simple/test-child-process-ipc.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; - -var path = require('path'); - -var sub = path.join(common.fixturesDir, 'echo.js'); - -var gotHelloWorld = false; -var gotEcho = false; - -var child = spawn(process.argv[0], [sub]); - -child.stderr.on('data', function(data) { - console.log('parent stderr: ' + data); -}); - -child.stdout.setEncoding('utf8'); - -child.stdout.on('data', function(data) { - console.log('child said: ' + JSON.stringify(data)); - if (!gotHelloWorld) { - console.error('testing for hello world'); - assert.equal('hello world\r\n', data); - gotHelloWorld = true; - console.error('writing echo me'); - child.stdin.write('echo me\r\n'); - } else { - console.error('testing for echo me'); - assert.equal('echo me\r\n', data); - gotEcho = true; - child.stdin.end(); - } -}); - -child.stdout.on('end', function(data) { - console.log('child end'); -}); - - -process.on('exit', function() { - assert.ok(gotHelloWorld); - assert.ok(gotEcho); -}); diff --git a/test/simple/test-child-process-kill.js b/test/simple/test-child-process-kill.js deleted file mode 100644 index 08a0185d3..000000000 --- a/test/simple/test-child-process-kill.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; - -var is_windows = process.platform === 'win32'; - -var exitCode; -var termSignal; -var gotStdoutEOF = false; -var gotStderrEOF = false; - -var cat = spawn(is_windows ? 'cmd' : 'cat'); - - -cat.stdout.on('end', function() { - gotStdoutEOF = true; -}); - -cat.stderr.on('data', function(chunk) { - assert.ok(false); -}); - -cat.stderr.on('end', function() { - gotStderrEOF = true; -}); - -cat.on('exit', function(code, signal) { - exitCode = code; - termSignal = signal; -}); - -assert.equal(cat.killed, false); -cat.kill(); -assert.equal(cat.killed, true); - -process.on('exit', function() { - assert.strictEqual(exitCode, null); - assert.strictEqual(termSignal, 'SIGTERM'); - assert.ok(gotStdoutEOF); - assert.ok(gotStderrEOF); -}); diff --git a/test/simple/test-child-process-recv-handle.js b/test/simple/test-child-process-recv-handle.js deleted file mode 100644 index dce5bdcba..000000000 --- a/test/simple/test-child-process-recv-handle.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Test that a Linux specific quirk in the handle passing protocol is handled -// correctly. See https://github.com/joyent/node/issues/5330 for details. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var spawn = require('child_process').spawn; - -if (process.argv[2] === 'worker') - worker(); -else - master(); - -function master() { - // spawn() can only create one IPC channel so we use stdin/stdout as an - // ad-hoc command channel. - var proc = spawn(process.execPath, [__filename, 'worker'], { - stdio: ['pipe', 'pipe', 'pipe', 'ipc'] - }); - var handle = null; - proc.on('exit', function() { - handle.close(); - }); - proc.stdout.on('data', function(data) { - assert.equal(data, 'ok\r\n'); - net.createServer(assert.fail).listen(common.PORT, function() { - handle = this._handle; - proc.send('one'); - proc.send('two', handle); - proc.send('three'); - proc.stdin.write('ok\r\n'); - }); - }); - proc.stderr.pipe(process.stderr); -} - -function worker() { - process._channel.readStop(); // Make messages batch up. - process.stdout.ref(); - process.stdout.write('ok\r\n'); - process.stdin.once('data', function(data) { - assert.equal(data, 'ok\r\n'); - process._channel.readStart(); - }); - var n = 0; - process.on('message', function(msg, handle) { - n += 1; - if (n === 1) { - assert.equal(msg, 'one'); - assert.equal(handle, undefined); - } - else if (n === 2) { - assert.equal(msg, 'two'); - assert.equal(typeof handle, 'object'); // Also matches null, therefore... - assert.ok(handle); // also check that it's truthy. - handle.close(); - } - else if (n === 3) { - assert.equal(msg, 'three'); - assert.equal(handle, undefined); - process.exit(); - } - }); -} diff --git a/test/simple/test-child-process-send-utf8.js b/test/simple/test-child-process-send-utf8.js deleted file mode 100644 index b3ce24390..000000000 --- a/test/simple/test-child-process-send-utf8.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; - -var expected = Array(1e5).join('ßßßß'); -if (process.argv[2] === 'child') { - process.send(expected); -} else { - var child = fork(process.argv[1], ['child']); - child.on('message', common.mustCall(function(actual) { - assert.equal(actual, expected); - })); -} diff --git a/test/simple/test-child-process-set-blocking.js b/test/simple/test-child-process-set-blocking.js deleted file mode 100644 index e07c6cc4d..000000000 --- a/test/simple/test-child-process-set-blocking.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var ch = require('child_process'); - -var SIZE = 100000; -var childGone = false; - -var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { - stdio: 'inherit' -}); - -cp.on('exit', function(code) { - childGone = true; - assert.equal(0, code); -}); - -process.on('exit', function() { - assert.ok(childGone); -}); diff --git a/test/simple/test-child-process-silent.js b/test/simple/test-child-process-silent.js deleted file mode 100644 index e34daa3a8..000000000 --- a/test/simple/test-child-process-silent.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var childProcess = require('child_process'); - -// Child pipe test -if (process.argv[2] === 'pipetest') { - process.stdout.write('stdout message'); - process.stderr.write('stderr message'); - -} else if (process.argv[2] === 'ipctest') { - // Child IPC test - process.send('message from child'); - process.on('message', function() { - process.send('got message from master'); - }); - -} else if (process.argv[2] === 'parent') { - // Parent | start child pipe test - - var child = childProcess.fork(process.argv[1], ['pipetest'], {silent: true}); - - // Allow child process to self terminate - child._channel.close(); - child._channel = null; - - child.on('exit', function() { - process.exit(0); - }); - -} else { - // testcase | start parent && child IPC test - - // testing: is stderr and stdout piped to parent - var args = [process.argv[1], 'parent']; - var parent = childProcess.spawn(process.execPath, args); - - //got any stderr or std data - var stdoutData = false; - parent.stdout.on('data', function() { - stdoutData = true; - }); - var stderrData = false; - parent.stdout.on('data', function() { - stderrData = true; - }); - - // testing: do message system work when using silent - var child = childProcess.fork(process.argv[1], ['ipctest'], {silent: true}); - - // Manual pipe so we will get errors - child.stderr.pipe(process.stderr, {end: false}); - child.stdout.pipe(process.stdout, {end: false}); - - var childSending = false; - var childReciveing = false; - child.on('message', function(message) { - if (childSending === false) { - childSending = (message === 'message from child'); - } - - if (childReciveing === false) { - childReciveing = (message === 'got message from master'); - } - - if (childReciveing === true) { - child.kill(); - } - }); - child.send('message to child'); - - // Check all values - process.on('exit', function() { - // clean up - child.kill(); - parent.kill(); - - // Check std(out|err) pipes - assert.ok(!stdoutData, 'The stdout socket was piped to parent'); - assert.ok(!stderrData, 'The stderr socket was piped to parent'); - - // Check message system - assert.ok(childSending, 'The child was able to send a message'); - assert.ok(childReciveing, 'The child was able to receive a message'); - }); -} diff --git a/test/simple/test-child-process-spawn-error.js b/test/simple/test-child-process-spawn-error.js deleted file mode 100644 index 5ecfbff26..000000000 --- a/test/simple/test-child-process-spawn-error.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var fs = require('fs'); -var spawn = require('child_process').spawn; -var assert = require('assert'); - -var errors = 0; - -var enoentPath = 'foo123'; -assert.equal(fs.existsSync(enoentPath), false); - -var enoentChild = spawn(enoentPath); -enoentChild.on('error', function (err) { - assert.equal(err.path, enoentPath); - errors++; -}); - -process.on('exit', function() { - assert.equal(1, errors); -}); diff --git a/test/simple/test-child-process-spawn-typeerror.js b/test/simple/test-child-process-spawn-typeerror.js deleted file mode 100644 index 4fd360a3f..000000000 --- a/test/simple/test-child-process-spawn-typeerror.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var spawn = require('child_process').spawn, - assert = require('assert'), - windows = (process.platform === 'win32'), - cmd = (windows) ? 'rundll32' : 'ls', - invalidcmd = 'hopefully_you_dont_have_this_on_your_machine', - invalidArgsMsg = /Incorrect value of args option/, - invalidOptionsMsg = /options argument must be an object/, - errors = 0; - -try { - // Ensure this throws a TypeError - var child = spawn(invalidcmd, 'this is not an array'); - - child.on('error', function (err) { - errors++; - }); - -} catch (e) { - assert.equal(e instanceof TypeError, true); -} - -// verify that valid argument combinations do not throw -assert.doesNotThrow(function() { - spawn(cmd); -}); - -assert.doesNotThrow(function() { - spawn(cmd, []); -}); - -assert.doesNotThrow(function() { - spawn(cmd, {}); -}); - -assert.doesNotThrow(function() { - spawn(cmd, [], {}); -}); - -// verify that invalid argument combinations throw -assert.throws(function() { - spawn(); -}, /Bad argument/); - -assert.throws(function() { - spawn(cmd, null); -}, invalidArgsMsg); - -assert.throws(function() { - spawn(cmd, true); -}, invalidArgsMsg); - -assert.throws(function() { - spawn(cmd, [], null); -}, invalidOptionsMsg); - -assert.throws(function() { - spawn(cmd, [], 1); -}, invalidOptionsMsg); - -process.on('exit', function() { - assert.equal(errors, 0); -}); diff --git a/test/simple/test-child-process-spawnsync-env.js b/test/simple/test-child-process-spawnsync-env.js deleted file mode 100644 index 0cde9ffee..000000000 --- a/test/simple/test-child-process-spawnsync-env.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cp = require('child_process'); - -if (process.argv[2] === 'child') { - console.log(process.env.foo); -} else { - var expected = 'bar'; - var child = cp.spawnSync(process.execPath, [__filename, 'child'], { - env: {foo: expected} - }); - - assert.equal(child.stdout.toString().trim(), expected); -} diff --git a/test/simple/test-child-process-spawnsync-input.js b/test/simple/test-child-process-spawnsync-input.js deleted file mode 100644 index 66b2fa354..000000000 --- a/test/simple/test-child-process-spawnsync-input.js +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var os = require('os'); -var util = require('util'); - -var spawnSync = require('child_process').spawnSync; - -var msgOut = 'this is stdout'; -var msgErr = 'this is stderr'; - -// this is actually not os.EOL? -var msgOutBuf = new Buffer(msgOut + '\n'); -var msgErrBuf = new Buffer(msgErr + '\n'); - -var args = [ - '-e', - util.format('console.log("%s"); console.error("%s");', msgOut, msgErr) -]; - -var ret; - - -if (process.argv.indexOf('spawnchild') !== -1) { - switch (process.argv[3]) { - case '1': - ret = spawnSync(process.execPath, args, { stdio: 'inherit' }); - common.checkSpawnSyncRet(ret); - break; - case '2': - ret = spawnSync(process.execPath, args, { - stdio: ['inherit', 'inherit', 'inherit'] - }); - common.checkSpawnSyncRet(ret); - break; - } - process.exit(0); - return; -} - - -function verifyBufOutput(ret) { - common.checkSpawnSyncRet(ret); - assert.deepEqual(ret.stdout, msgOutBuf); - assert.deepEqual(ret.stderr, msgErrBuf); -} - - -verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 1])); -verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 2])); - -var options = { - input: 1234 -}; - -assert.throws(function() { - spawnSync('cat', [], options); -}, /TypeError:.*should be Buffer or string not number/); - - -options = { - input: 'hello world' -}; - -ret = spawnSync('cat', [], options); - -common.checkSpawnSyncRet(ret); -assert.strictEqual(ret.stdout.toString('utf8'), options.input); -assert.strictEqual(ret.stderr.toString('utf8'), ''); - -options = { - input: new Buffer('hello world') -}; - -ret = spawnSync('cat', [], options); - -common.checkSpawnSyncRet(ret); -assert.deepEqual(ret.stdout, options.input); -assert.deepEqual(ret.stderr, new Buffer('')); - -verifyBufOutput(spawnSync(process.execPath, args)); - -ret = spawnSync(process.execPath, args, { encoding: 'utf8' }); - -common.checkSpawnSyncRet(ret); -assert.strictEqual(ret.stdout, msgOut + '\n'); -assert.strictEqual(ret.stderr, msgErr + '\n'); - -options = { - maxBuffer: 1 -}; - -ret = spawnSync(process.execPath, args, options); - -assert.ok(ret.error, 'maxBuffer should error'); -assert.strictEqual(ret.error.errno, 'ENOBUFS'); -// we can have buffers larger than maxBuffer because underneath we alloc 64k -// that matches our read sizes -assert.deepEqual(ret.stdout, msgOutBuf); diff --git a/test/simple/test-child-process-spawnsync-timeout.js b/test/simple/test-child-process-spawnsync-timeout.js deleted file mode 100644 index 691f58786..000000000 --- a/test/simple/test-child-process-spawnsync-timeout.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawnSync = require('child_process').spawnSync; - -var TIMER = 200; -var SLEEP = 1000; - -switch (process.argv[2]) { - case 'child': - setTimeout(function() { - console.log('child fired'); - process.exit(1); - }, SLEEP); - break; - default: - var start = Date.now(); - var ret = spawnSync(process.execPath, [__filename, 'child'], {timeout: TIMER}); - assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); - console.log(ret); - var end = Date.now() - start; - assert(end < SLEEP); - assert(ret.status > 128 || ret.signal); - break; -} diff --git a/test/simple/test-child-process-spawnsync.js b/test/simple/test-child-process-spawnsync.js deleted file mode 100644 index a7cbb8d1d..000000000 --- a/test/simple/test-child-process-spawnsync.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawnSync = require('child_process').spawnSync; - -var TIMER = 100; -var SLEEP = 1000; - -var timeout = 0; - -setTimeout(function() { - timeout = process.hrtime(start); - assert.ok(stop, 'timer should not fire before process exits'); - assert.strictEqual(timeout[0], 1, 'timer should take as long as sleep'); -}, TIMER); - -console.log('sleep started'); -var start = process.hrtime(); -var ret = spawnSync('sleep', ['1']); -var stop = process.hrtime(start); -assert.strictEqual(ret.status, 0, 'exit status should be zero'); -console.log('sleep exited', stop); -assert.strictEqual(stop[0], 1, 'sleep should not take longer or less than 1 second'); - -// Error test when command does not exist -var ret_err = spawnSync('command_does_not_exist'); -assert.strictEqual(ret_err.error.code, 'ENOENT'); - -// Verify that the cwd option works - GH #7824 -(function() { - var response; - var cwd; - - if (process.platform === 'win32') { - cwd = 'c:\\'; - response = spawnSync('cmd.exe', ['/c', 'cd'], {cwd: cwd}); - } else { - cwd = '/'; - response = spawnSync('pwd', [], {cwd: cwd}); - } - - assert.strictEqual(response.stdout.toString().trim(), cwd); -})(); diff --git a/test/simple/test-child-process-stdin-ipc.js b/test/simple/test-child-process-stdin-ipc.js deleted file mode 100644 index cd6a921d0..000000000 --- a/test/simple/test-child-process-stdin-ipc.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; - -if (process.argv[2] === 'child') { - // Just reference stdin, it should start it - process.stdin; - return; -} - -var proc = spawn(process.execPath, [__filename, 'child'], { - stdio: ['ipc', 'inherit', 'inherit'] -}); - -var childCode = -1; -proc.on('exit', function(code) { - childCode = code; -}); - -process.on('exit', function() { - assert.equal(childCode, 0); -}); diff --git a/test/simple/test-child-process-stdin.js b/test/simple/test-child-process-stdin.js deleted file mode 100644 index fdb40cc82..000000000 --- a/test/simple/test-child-process-stdin.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; -var is_windows = process.platform === 'win32'; - -var cat = spawn(is_windows ? 'more' : 'cat'); -cat.stdin.write('hello'); -cat.stdin.write(' '); -cat.stdin.write('world'); - -assert.ok(cat.stdin.writable); -assert.ok(!cat.stdin.readable); - -cat.stdin.end(); - -var response = ''; -var exitStatus = -1; -var closed = false; - -var gotStdoutEOF = false; - -cat.stdout.setEncoding('utf8'); -cat.stdout.on('data', function(chunk) { - console.log('stdout: ' + chunk); - response += chunk; -}); - -cat.stdout.on('end', function() { - gotStdoutEOF = true; -}); - - -var gotStderrEOF = false; - -cat.stderr.on('data', function(chunk) { - // shouldn't get any stderr output - assert.ok(false); -}); - -cat.stderr.on('end', function(chunk) { - gotStderrEOF = true; -}); - - -cat.on('exit', function(status) { - console.log('exit event'); - exitStatus = status; -}); - -cat.on('close', function () { - closed = true; - if (is_windows) { - assert.equal('hello world\r\n', response); - } else { - assert.equal('hello world', response); - } -}); - -process.on('exit', function() { - assert.equal(0, exitStatus); - assert(closed); - if (is_windows) { - assert.equal('hello world\r\n', response); - } else { - assert.equal('hello world', response); - } -}); diff --git a/test/simple/test-child-process-stdio-big-write-end.js b/test/simple/test-child-process-stdio-big-write-end.js deleted file mode 100644 index 845a23e66..000000000 --- a/test/simple/test-child-process-stdio-big-write-end.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var BUFSIZE = 1024; - -switch (process.argv[2]) { - case undefined: - return parent(); - case 'child': - return child(); - default: - throw new Error('wtf?'); -} - -function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); - var sent = 0; - - var n = ''; - child.stdout.setEncoding('ascii'); - child.stdout.on('data', function(c) { - n += c; - }); - child.stdout.on('end', function() { - assert.equal(+n, sent); - console.log('ok'); - }); - - // Write until the buffer fills up. - do { - var buf = new Buffer(BUFSIZE); - buf.fill('.'); - sent += BUFSIZE; - } while (child.stdin.write(buf)); - - // then write a bunch more times. - for (var i = 0; i < 100; i++) { - var buf = new Buffer(BUFSIZE); - buf.fill('.'); - sent += BUFSIZE; - child.stdin.write(buf); - } - - // now end, before it's all flushed. - child.stdin.end(); - - // now we wait... -} - -function child() { - var received = 0; - process.stdin.on('data', function(c) { - received += c.length; - }); - process.stdin.on('end', function() { - console.log(received); - }); -} diff --git a/test/simple/test-child-process-stdio-inherit.js b/test/simple/test-child-process-stdio-inherit.js deleted file mode 100644 index f7776fecb..000000000 --- a/test/simple/test-child-process-stdio-inherit.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -if (process.argv[2] === 'parent') - parent(); -else - grandparent(); - -function grandparent() { - var child = spawn(process.execPath, [__filename, 'parent']); - child.stderr.pipe(process.stderr); - var output = ''; - var input = 'asdfasdf'; - - child.stdout.on('data', function(chunk) { - output += chunk; - }); - child.stdout.setEncoding('utf8'); - - child.stdin.end(input); - - child.on('close', function(code, signal) { - assert.equal(code, 0); - assert.equal(signal, null); - // cat on windows adds a \r\n at the end. - assert.equal(output.trim(), input.trim()); - }); -} - -function parent() { - // should not immediately exit. - var child = common.spawnCat({ stdio: 'inherit' }); -} diff --git a/test/simple/test-child-process-stdio.js b/test/simple/test-child-process-stdio.js deleted file mode 100644 index 32da15f5f..000000000 --- a/test/simple/test-child-process-stdio.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -var options = {stdio: ['pipe']}; -var child = common.spawnPwd(options); - -assert.notEqual(child.stdout, null); -assert.notEqual(child.stderr, null); - -options = {stdio: 'ignore'}; -child = common.spawnPwd(options); - -assert.equal(child.stdout, null); -assert.equal(child.stderr, null); diff --git a/test/simple/test-child-process-stdout-flush-exit.js b/test/simple/test-child-process-stdout-flush-exit.js deleted file mode 100644 index 49a0ec0e5..000000000 --- a/test/simple/test-child-process-stdout-flush-exit.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); - -// if child process output to console and exit -if (process.argv[2] === 'child') { - console.log('hello'); - for (var i = 0; i < 200; i++) { - console.log('filler'); - } - console.log('goodbye'); - process.exit(0); -} else { - // parent process - var spawn = require('child_process').spawn; - - // spawn self as child - var child = spawn(process.argv[0], [process.argv[1], 'child']); - - var gotHello = false; - var gotBye = false; - - child.stderr.setEncoding('utf8'); - child.stderr.on('data', function (data) { - console.log('parent stderr: ' + data); - assert.ok(false); - }); - - // check if we receive both 'hello' at start and 'goodbye' at end - child.stdout.setEncoding('utf8'); - child.stdout.on('data', function (data) { - if (data.slice(0, 6) == 'hello\n') { - gotHello = true; - } else if (data.slice(data.length - 8) == 'goodbye\n') { - gotBye = true; - } else { - gotBye = false; - } - }); - - child.on('close', function (data) { - assert(gotHello); - assert(gotBye); - }); -} diff --git a/test/simple/test-child-process-stdout-flush.js b/test/simple/test-child-process-stdout-flush.js deleted file mode 100644 index adb33f5c0..000000000 --- a/test/simple/test-child-process-stdout-flush.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var spawn = require('child_process').spawn; -var sub = path.join(common.fixturesDir, 'print-chars.js'); - -var n = 500000; - -var child = spawn(process.argv[0], [sub, n]); - -var count = 0; - -child.stderr.setEncoding('utf8'); -child.stderr.on('data', function(data) { - console.log('parent stderr: ' + data); - assert.ok(false); -}); - -child.stdout.setEncoding('utf8'); -child.stdout.on('data', function(data) { - count += data.length; - console.log(count); -}); - -child.on('close', function(data) { - assert.equal(n, count); - console.log('okay'); -}); diff --git a/test/simple/test-cli-eval.js b/test/simple/test-cli-eval.js deleted file mode 100644 index d265601e8..000000000 --- a/test/simple/test-cli-eval.js +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (module.parent) { - // signal we've been loaded as a module - console.log('Loaded as a module, exiting with status code 42.'); - process.exit(42); -} - -var common = require('../common.js'), - assert = require('assert'), - child = require('child_process'), - nodejs = '"' + process.execPath + '"'; - - -// replace \ by / because windows uses backslashes in paths, but they're still -// interpreted as the escape character when put between quotes. -var filename = __filename.replace(/\\/g, '/'); - -// assert that nothing is written to stdout -child.exec(nodejs + ' --eval 42', - function(err, stdout, stderr) { - assert.equal(stdout, ''); - assert.equal(stderr, ''); - }); - -// assert that "42\n" is written to stderr -child.exec(nodejs + ' --eval "console.error(42)"', - function(err, stdout, stderr) { - assert.equal(stdout, ''); - assert.equal(stderr, '42\n'); - }); - -// assert that the expected output is written to stdout -['--print', '-p -e', '-pe', '-p'].forEach(function(s) { - var cmd = nodejs + ' ' + s + ' '; - - child.exec(cmd + '42', - function(err, stdout, stderr) { - assert.equal(stdout, '42\n'); - assert.equal(stderr, ''); - }); - - child.exec(cmd + "'[]'", - function(err, stdout, stderr) { - assert.equal(stdout, '[]\n'); - assert.equal(stderr, ''); - }); -}); - -// assert that module loading works -child.exec(nodejs + ' --eval "require(\'' + filename + '\')"', - function(status, stdout, stderr) { - assert.equal(status.code, 42); - }); - -// module path resolve bug, regression test -child.exec(nodejs + ' --eval "require(\'./test/simple/test-cli-eval.js\')"', - function(status, stdout, stderr) { - assert.equal(status.code, 42); - }); - -// empty program should do nothing -child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { - assert.equal(stdout, ''); - assert.equal(stderr, ''); -}); - -// "\\-42" should be interpreted as an escaped expression, not a switch -child.exec(nodejs + ' -p "\\-42"', - function(err, stdout, stderr) { - assert.equal(stdout, '-42\n'); - assert.equal(stderr, ''); - }); - -child.exec(nodejs + ' --use-strict -p process.execArgv', - function(status, stdout, stderr) { - assert.equal(stdout, "[ '--use-strict', '-p', 'process.execArgv' ]\n"); - }); diff --git a/test/simple/test-cluster-basic.js b/test/simple/test-cluster-basic.js deleted file mode 100644 index e6adfb5ba..000000000 --- a/test/simple/test-cluster-basic.js +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -assert.equal('NODE_UNIQUE_ID' in process.env, false, - 'NODE_UNIQUE_ID should be removed on startup'); - -function forEach(obj, fn) { - Object.keys(obj).forEach(function(name, index) { - fn(obj[name], name, index); - }); -} - - -if (cluster.isWorker) { - var http = require('http'); - http.Server(function() { - - }).listen(common.PORT, '127.0.0.1'); -} - -else if (cluster.isMaster) { - - var checks = { - cluster: { - events: { - fork: false, - online: false, - listening: false, - exit: false - }, - equal: { - fork: false, - online: false, - listening: false, - exit: false - } - }, - - worker: { - events: { - online: false, - listening: false, - exit: false - }, - equal: { - online: false, - listening: false, - exit: false - }, - states: { - none: false, - online: false, - listening: false, - dead: false - } - } - }; - - var worker; - var stateNames = Object.keys(checks.worker.states); - - //Check events, states, and emit arguments - forEach(checks.cluster.events, function(bool, name, index) { - - //Listen on event - cluster.on(name, function(/* worker */) { - - //Set event - checks.cluster.events[name] = true; - - //Check argument - checks.cluster.equal[name] = worker === arguments[0]; - - //Check state - var state = stateNames[index]; - checks.worker.states[state] = (state === worker.state); - }); - }); - - //Kill worker when listening - cluster.on('listening', function() { - worker.kill(); - }); - - //Kill process when worker is killed - cluster.on('exit', function() { - process.exit(0); - }); - - //Create worker - worker = cluster.fork(); - assert.equal(worker.id, 1); - assert.ok(worker instanceof cluster.Worker, - 'the worker is not a instance of the Worker constructor'); - - //Check event - forEach(checks.worker.events, function(bool, name, index) { - worker.on(name, function() { - //Set event - checks.worker.events[name] = true; - - //Check argument - checks.worker.equal[name] = (worker === this); - - switch (name) { - case 'exit': - assert.equal(arguments[0], worker.process.exitCode); - assert.equal(arguments[1], worker.process.signalCode); - assert.equal(arguments.length, 2); - break; - - case 'listening': - assert.equal(arguments.length, 1); - var expect = { address: '127.0.0.1', - port: common.PORT, - addressType: 4, - fd: undefined }; - assert.deepEqual(arguments[0], expect); - break; - - default: - assert.equal(arguments.length, 0); - break; - } - }); - }); - - //Check all values - process.once('exit', function() { - //Check cluster events - forEach(checks.cluster.events, function(check, name) { - assert.ok(check, 'The cluster event "' + name + '" on the cluster ' + - 'object did not fire'); - }); - - //Check cluster event arguments - forEach(checks.cluster.equal, function(check, name) { - assert.ok(check, 'The cluster event "' + name + '" did not emit ' + - 'with correct argument'); - }); - - //Check worker states - forEach(checks.worker.states, function(check, name) { - assert.ok(check, 'The worker state "' + name + '" was not set to true'); - }); - - //Check worker events - forEach(checks.worker.events, function(check, name) { - assert.ok(check, 'The worker event "' + name + '" on the worker object ' + - 'did not fire'); - }); - - //Check worker event arguments - forEach(checks.worker.equal, function(check, name) { - assert.ok(check, 'The worker event "' + name + '" did not emit with ' + - 'corrent argument'); - }); - }); - -} diff --git a/test/simple/test-cluster-bind-privileged-port.js b/test/simple/test-cluster-bind-privileged-port.js deleted file mode 100644 index b76757728..000000000 --- a/test/simple/test-cluster-bind-privileged-port.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (process.platform === 'win32') { - console.log('Skipping test, not reliable on Windows.'); - process.exit(0); -} - -if (process.getuid() === 0) { - console.log('Do not run this test as root.'); - process.exit(0); -} - -if (cluster.isMaster) { - cluster.fork().on('exit', common.mustCall(function(exitCode) { - assert.equal(exitCode, 0); - })); -} -else { - var s = net.createServer(assert.fail); - s.listen(42, assert.fail.bind(null, 'listen should have failed')); - s.on('error', common.mustCall(function(err) { - assert.equal(err.code, 'EACCES'); - process.disconnect(); - })); -} diff --git a/test/simple/test-cluster-bind-twice.js b/test/simple/test-cluster-bind-twice.js deleted file mode 100644 index 311bc60fa..000000000 --- a/test/simple/test-cluster-bind-twice.js +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This test starts two clustered HTTP servers on the same port. It expects the -// first cluster to succeed and the second cluster to fail with EADDRINUSE. -// -// The test may seem complex but most of it is plumbing that routes messages -// from the child processes back to the supervisor. As a tree it looks something -// like this: -// -// -// / \ -// -// / \ -// -// -// The first worker starts a server on a fixed port and fires a ready message -// that is routed to the second worker. When it tries to bind, it expects to -// see an EADDRINUSE error. -// -// See https://github.com/joyent/node/issues/2721 for more details. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var fork = require('child_process').fork; -var http = require('http'); - -var id = process.argv[2]; - -if (!id) { - var a = fork(__filename, ['one']); - var b = fork(__filename, ['two']); - - a.on('exit', function(c) { - if (c) { - b.send('QUIT'); - throw new Error('A exited with ' + c); - } - }); - - b.on('exit', function(c) { - if (c) { - a.send('QUIT'); - throw new Error('B exited with ' + c); - } - }); - - - a.on('message', function(m) { - if (typeof m === 'object') return; - assert.equal(m, 'READY'); - b.send('START'); - }); - - var ok = false; - - b.on('message', function(m) { - if (typeof m === 'object') return; // ignore system messages - assert.equal(m, 'EADDRINUSE'); - ok = true; - a.send('QUIT'); - b.send('QUIT'); - }); - - process.on('exit', function() { - assert(ok); - }); -} -else if (id === 'one') { - if (cluster.isMaster) return startWorker(); - - var server = http.createServer(assert.fail).listen(common.PORT, function() { - process.send('READY'); - }); - - process.on('message', function(m) { - if (m === 'QUIT') process.exit(); - }); -} -else if (id === 'two') { - if (cluster.isMaster) return startWorker(); - - var ok = false; - process.on('exit', function() { - assert(ok); - }); - - var server = http.createServer(assert.fail); - process.on('message', function(m) { - if (typeof m === 'object') return; // ignore system messages - if (m === 'QUIT') process.exit(); - assert.equal(m, 'START'); - server.listen(common.PORT, assert.fail); - server.on('error', function(e) { - assert.equal(e.code, 'EADDRINUSE'); - process.send(e.code); - ok = true; - }); - }); -} -else { - assert(0); // bad command line argument -} - -function startWorker() { - var worker = cluster.fork(); - worker.on('exit', process.exit); - worker.on('message', process.send.bind(process)); - process.on('message', worker.send.bind(worker)); -} diff --git a/test/simple/test-cluster-dgram-1.js b/test/simple/test-cluster-dgram-1.js deleted file mode 100644 index c6dc095d0..000000000 --- a/test/simple/test-cluster-dgram-1.js +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var NUM_WORKERS = 4; -var PACKETS_PER_WORKER = 10; - -var assert = require('assert'); -var cluster = require('cluster'); -var common = require('../common'); -var dgram = require('dgram'); - - -if (process.platform === 'win32') { - console.warn("dgram clustering is currently not supported on windows."); - process.exit(0); -} - -if (cluster.isMaster) - master(); -else - worker(); - - -function master() { - var listening = 0; - - // Fork 4 workers. - for (var i = 0; i < NUM_WORKERS; i++) - cluster.fork(); - - // Wait until all workers are listening. - cluster.on('listening', function() { - if (++listening < NUM_WORKERS) - return; - - // Start sending messages. - var buf = new Buffer('hello world'); - var socket = dgram.createSocket('udp4'); - var sent = 0; - doSend(); - - function doSend() { - socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1', afterSend); - } - - function afterSend() { - sent++; - if (sent < NUM_WORKERS * PACKETS_PER_WORKER) { - doSend(); - } else { - console.log('master sent %d packets', sent); - socket.close(); - } - } - }); - - // Set up event handlers for every worker. Each worker sends a message when - // it has received the expected number of packets. After that it disconnects. - for (var key in cluster.workers) { - if (cluster.workers.hasOwnProperty(key)) - setupWorker(cluster.workers[key]); - } - - function setupWorker(worker) { - var received = 0; - - worker.on('message', function(msg) { - received = msg.received; - console.log('worker %d received %d packets', worker.id, received); - }); - - worker.on('disconnect', function() { - assert(received === PACKETS_PER_WORKER); - console.log('worker %d disconnected', worker.id); - }); - } -} - - -function worker() { - var received = 0; - - // Create udp socket and start listening. - var socket = dgram.createSocket('udp4'); - - socket.on('message', function(data, info) { - received++; - - // Every 10 messages, notify the master. - if (received == PACKETS_PER_WORKER) { - process.send({received: received}); - process.disconnect(); - } - }); - - socket.bind(common.PORT); -} diff --git a/test/simple/test-cluster-dgram-2.js b/test/simple/test-cluster-dgram-2.js deleted file mode 100644 index cb5eaf067..000000000 --- a/test/simple/test-cluster-dgram-2.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var NUM_WORKERS = 4; -var PACKETS_PER_WORKER = 10; - -var assert = require('assert'); -var cluster = require('cluster'); -var common = require('../common'); -var dgram = require('dgram'); - - -if (process.platform === 'win32') { - console.warn("dgram clustering is currently not supported on windows."); - process.exit(0); -} - -if (cluster.isMaster) - master(); -else - worker(); - - -function master() { - var i; - var received = 0; - - // Start listening on a socket. - var socket = dgram.createSocket('udp4'); - socket.bind(common.PORT); - - // Disconnect workers when the expected number of messages have been - // received. - socket.on('message', function(data, info) { - received++; - - if (received == PACKETS_PER_WORKER * NUM_WORKERS) { - console.log('master received %d packets', received); - - // Close the socket. - socket.close(); - - // Disconnect all workers. - cluster.disconnect(); - } - }); - - // Fork workers. - for (var i = 0; i < NUM_WORKERS; i++) - cluster.fork(); -} - - -function worker() { - // Create udp socket and send packets to master. - var socket = dgram.createSocket('udp4'); - var buf = new Buffer('hello world'); - - for (var i = 0; i < PACKETS_PER_WORKER; i++) - socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1'); - - console.log('worker %d sent %d packets', cluster.worker.id, PACKETS_PER_WORKER); -} diff --git a/test/simple/test-cluster-disconnect-idle-worker.js b/test/simple/test-cluster-disconnect-idle-worker.js deleted file mode 100644 index 9c79ad779..000000000 --- a/test/simple/test-cluster-disconnect-idle-worker.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (cluster.isMaster) { - cluster.fork(); - cluster.fork(); - cluster.disconnect(common.mustCall(function() { - assert.deepEqual(Object.keys(cluster.workers), []); - })); -} diff --git a/test/simple/test-cluster-disconnect-with-no-workers.js b/test/simple/test-cluster-disconnect-with-no-workers.js deleted file mode 100644 index 48e3b0925..000000000 --- a/test/simple/test-cluster-disconnect-with-no-workers.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var cluster = require('cluster'); - -var disconnected; - -process.on('exit', function() { - assert(disconnected); -}); - -cluster.disconnect(function() { - disconnected = true; -}); - -// Assert that callback is not sometimes synchronous -assert(!disconnected); diff --git a/test/simple/test-cluster-disconnect.js b/test/simple/test-cluster-disconnect.js deleted file mode 100644 index 797c17d76..000000000 --- a/test/simple/test-cluster-disconnect.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (cluster.isWorker) { - net.createServer(function(socket) { - socket.end('echo'); - }).listen(common.PORT, '127.0.0.1'); - - net.createServer(function(socket) { - socket.end('echo'); - }).listen(common.PORT + 1, '127.0.0.1'); - -} else if (cluster.isMaster) { - var servers = 2; - - // test a single TCP server - var testConnection = function(port, cb) { - var socket = net.connect(port, '127.0.0.1', function() { - // buffer result - var result = ''; - socket.on('data', function(chunk) { result += chunk; }); - - // check result - socket.on('end', function() { - cb(result === 'echo'); - }); - }); - }; - - // test both servers created in the cluster - var testCluster = function(cb) { - var done = 0; - - for (var i = 0, l = servers; i < l; i++) { - testConnection(common.PORT + i, function(success) { - assert.ok(success); - done += 1; - if (done === servers) { - cb(); - } - }); - } - }; - - // start two workers and execute callback when both is listening - var startCluster = function(cb) { - var workers = 8; - var online = 0; - - for (var i = 0, l = workers; i < l; i++) { - - var worker = cluster.fork(); - worker.on('listening', function() { - online += 1; - if (online === workers * servers) { - cb(); - } - }); - } - }; - - - var results = { - start: 0, - test: 0, - disconnect: 0 - }; - - var test = function(again) { - //1. start cluster - startCluster(function() { - results.start += 1; - - //2. test cluster - testCluster(function() { - results.test += 1; - - //3. disconnect cluster - cluster.disconnect(function() { - results.disconnect += 1; - - // run test again to confirm cleanup - if (again) { - test(); - } - }); - }); - }); - }; - - test(true); - - process.once('exit', function() { - assert.equal(results.start, 2); - assert.equal(results.test, 2); - assert.equal(results.disconnect, 2); - }); -} diff --git a/test/simple/test-cluster-eaccess.js b/test/simple/test-cluster-eaccess.js deleted file mode 100644 index d5584242c..000000000 --- a/test/simple/test-cluster-eaccess.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test that errors propagated from cluster children are properly received in their master -// creates an EADDRINUSE condition by also forking a child process to listen on a socket - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var fork = require('child_process').fork; -var fs = require('fs'); -var net = require('net'); - - -if (cluster.isMaster) { - var worker = cluster.fork(); - var gotError = 0; - worker.on('message', function(err) { - gotError++; - console.log(err); - assert.strictEqual('EADDRINUSE', err.code); - worker.disconnect(); - }); - process.on('exit', function() { - console.log('master exited'); - try { - fs.unlinkSync(common.PIPE); - } catch (e) { - } - assert.equal(gotError, 1); - }); -} else { - var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', { stdio: 'inherit' }); - - // message from the child indicates it's ready and listening - cp.on('message', function() { - var server = net.createServer().listen(common.PIPE, function() { - console.log('parent listening, should not be!'); - }); - - server.on('error', function(err) { - console.log('parent error, ending'); - // message to child process tells it to exit - cp.send('end'); - // propagate error to parent - process.send(err); - }); - }); -} diff --git a/test/simple/test-cluster-eaddrinuse.js b/test/simple/test-cluster-eaddrinuse.js deleted file mode 100644 index 73b1df0a5..000000000 --- a/test/simple/test-cluster-eaddrinuse.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Check that having a worker bind to a port that's already taken doesn't -// leave the master process in a confused state. Releasing the port and -// trying again should Just Work[TM]. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var fork = require('child_process').fork; -var net = require('net'); - -var id = '' + process.argv[2]; - -if (id === 'undefined') { - var server = net.createServer(assert.fail); - server.listen(common.PORT, function() { - var worker = fork(__filename, ['worker']); - worker.on('message', function(msg) { - if (msg !== 'stop-listening') return; - server.close(function() { - worker.send('stopped-listening'); - }); - }); - }); -} -else if (id === 'worker') { - var server = net.createServer(assert.fail); - server.listen(common.PORT, assert.fail); - server.on('error', common.mustCall(function(e) { - assert(e.code, 'EADDRINUSE'); - process.send('stop-listening'); - process.once('message', function(msg) { - if (msg !== 'stopped-listening') return; - server = net.createServer(assert.fail); - server.listen(common.PORT, common.mustCall(function() { - server.close(); - })); - }); - })); -} -else { - assert(0); // Bad argument. -} diff --git a/test/simple/test-cluster-fork-env.js b/test/simple/test-cluster-fork-env.js deleted file mode 100644 index a0b50aebd..000000000 --- a/test/simple/test-cluster-fork-env.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (cluster.isWorker) { - cluster.worker.send({ - prop: process.env['cluster_test_prop'], - overwrite: process.env['cluster_test_overwrite'] - }); - -} else if (cluster.isMaster) { - - var checks = { - using: false, - overwrite: false - }; - - // To check that the cluster extend on the process.env we will overwrite a - // property - process.env['cluster_test_overwrite'] = 'old'; - - // Fork worker - var worker = cluster.fork({ - 'cluster_test_prop': 'custom', - 'cluster_test_overwrite': 'new' - }); - - // Checks worker env - worker.on('message', function(data) { - checks.using = (data.prop === 'custom'); - checks.overwrite = (data.overwrite === 'new'); - process.exit(0); - }); - - process.once('exit', function() { - assert.ok(checks.using, 'The worker did not receive the correct env.'); - assert.ok(checks.overwrite, 'The custom environment did not overwrite ' + - 'the existing environment.'); - }); - -} diff --git a/test/simple/test-cluster-http-pipe.js b/test/simple/test-cluster-http-pipe.js deleted file mode 100644 index 7123bf627..000000000 --- a/test/simple/test-cluster-http-pipe.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// It is not possible to send pipe handles over the IPC pipe on Windows. -if (process.platform === 'win32') { - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var http = require('http'); - -if (cluster.isMaster) { - var ok = false; - var worker = cluster.fork(); - worker.on('message', function(msg) { - assert.equal(msg, 'DONE'); - ok = true; - }); - worker.on('exit', function() { - process.exit(); - }); - process.on('exit', function() { - assert(ok); - }); - return; -} - -http.createServer(function(req, res) { - assert.equal(req.connection.remoteAddress, undefined); - assert.equal(req.connection.localAddress, undefined); // TODO common.PIPE? - res.writeHead(200); - res.end('OK'); -}).listen(common.PIPE, function() { - var self = this; - http.get({ socketPath: common.PIPE, path: '/' }, function(res) { - res.resume(); - res.on('end', function(err) { - if (err) throw err; - process.send('DONE'); - process.exit(); - }); - }); -}); diff --git a/test/simple/test-cluster-listening-port.js b/test/simple/test-cluster-listening-port.js deleted file mode 100644 index 352c4d757..000000000 --- a/test/simple/test-cluster-listening-port.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (cluster.isMaster) { - var port = null; - cluster.fork(); - cluster.on('listening', function(worker, address) { - port = address.port; - // ensure that the port is not 0 or null - assert(port); - // ensure that the port is numerical - assert.strictEqual(typeof(port), 'number'); - worker.kill(); - }); - process.on('exit', function() { - // ensure that the 'listening' handler has been called - assert(port); - }); -} -else { - net.createServer(assert.fail).listen(0); -} diff --git a/test/simple/test-cluster-master-error.js b/test/simple/test-cluster-master-error.js deleted file mode 100644 index ee2ed9eb4..000000000 --- a/test/simple/test-cluster-master-error.js +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -// Cluster setup -if (cluster.isWorker) { - var http = require('http'); - http.Server(function() { - - }).listen(common.PORT, '127.0.0.1'); - -} else if (process.argv[2] === 'cluster') { - - var totalWorkers = 2; - - // Send PID to testcase process - var forkNum = 0; - cluster.on('fork', function forkEvent(worker) { - - // Send PID - process.send({ - cmd: 'worker', - workerPID: worker.process.pid - }); - - // Stop listening when done - if (++forkNum === totalWorkers) { - cluster.removeListener('fork', forkEvent); - } - }); - - // Throw accidently error when all workers are listening - var listeningNum = 0; - cluster.on('listening', function listeningEvent() { - - // When all workers are listening - if (++listeningNum === totalWorkers) { - // Stop listening - cluster.removeListener('listening', listeningEvent); - - // throw accidently error - process.nextTick(function() { - console.error('about to throw'); - throw new Error('accidently error'); - }); - } - - }); - - // Startup a basic cluster - cluster.fork(); - cluster.fork(); - -} else { - // This is the testcase - - var fork = require('child_process').fork; - - var isAlive = function(pid) { - try { - //this will throw an error if the process is dead - process.kill(pid, 0); - - return true; - } catch (e) { - return false; - } - }; - - var existMaster = false; - var existWorker = false; - - // List all workers - var workers = []; - - // Spawn a cluster process - var master = fork(process.argv[1], ['cluster'], {silent: true}); - - // Handle messages from the cluster - master.on('message', function(data) { - - // Add worker pid to list and progress tracker - if (data.cmd === 'worker') { - workers.push(data.workerPID); - } - }); - - // When cluster is dead - master.on('exit', function(code) { - - // Check that the cluster died accidently - existMaster = !!code; - - // Give the workers time to shut down - setTimeout(checkWorkers, 200); - - function checkWorkers() { - // When master is dead all workers should be dead to - var alive = false; - workers.forEach(function(pid) { - if (isAlive(pid)) { - alive = true; - } - }); - - // If a worker was alive this did not act as expected - existWorker = !alive; - } - }); - - process.once('exit', function() { - var m = 'The master did not die after an error was throwed'; - assert.ok(existMaster, m); - m = 'The workers did not die after an error in the master'; - assert.ok(existWorker, m); - }); - -} diff --git a/test/simple/test-cluster-master-kill.js b/test/simple/test-cluster-master-kill.js deleted file mode 100644 index 362540390..000000000 --- a/test/simple/test-cluster-master-kill.js +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (cluster.isWorker) { - - // keep the worker alive - var http = require('http'); - http.Server().listen(common.PORT, '127.0.0.1'); - -} else if (process.argv[2] === 'cluster') { - - var worker = cluster.fork(); - - // send PID info to testcase process - process.send({ - pid: worker.process.pid - }); - - // terminate the cluster process - worker.once('listening', function() { - setTimeout(function() { - process.exit(0); - }, 1000); - }); - -} else { - - // This is the testcase - var fork = require('child_process').fork; - - // is process alive helper - var isAlive = function(pid) { - try { - //this will throw an error if the process is dead - process.kill(pid, 0); - - return true; - } catch (e) { - return false; - } - }; - - // Spawn a cluster process - var master = fork(process.argv[1], ['cluster']); - - // get pid info - var pid = null; - master.once('message', function(data) { - pid = data.pid; - }); - - // When master is dead - var alive = true; - master.on('exit', function(code) { - - // make sure that the master died by purpose - assert.equal(code, 0); - - // check worker process status - setTimeout(function() { - alive = isAlive(pid); - }, 200); - }); - - process.once('exit', function() { - // cleanup: kill the worker if alive - if (alive) { - process.kill(pid); - } - - assert.equal(typeof pid, 'number', 'did not get worker pid info'); - assert.equal(alive, false, 'worker was alive after master died'); - }); - -} diff --git a/test/simple/test-cluster-message.js b/test/simple/test-cluster-message.js deleted file mode 100644 index 7407515ad..000000000 --- a/test/simple/test-cluster-message.js +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -function forEach(obj, fn) { - Object.keys(obj).forEach(function(name, index) { - fn(obj[name], name, index); - }); -} - -if (cluster.isWorker) { - // Create a tcp server. This will be used as cluster-shared-server and as an - // alternative IPC channel. - var server = net.Server(); - var socket, message; - - function maybeReply() { - if (!socket || !message) return; - - // Tell master using TCP socket that a message is received. - socket.write(JSON.stringify({ - code: 'received message', - echo: message - })); - } - - server.on('connection', function(socket_) { - socket = socket_; - maybeReply(); - - // Send a message back over the IPC channel. - process.send('message from worker'); - }); - - process.on('message', function(message_) { - message = message_; - maybeReply(); - }); - - server.listen(common.PORT, '127.0.0.1'); -} - -else if (cluster.isMaster) { - - var checks = { - master: { - 'receive': false, - 'correct': false - }, - worker: { - 'receive': false, - 'correct': false - } - }; - - - var client; - var check = function(type, result) { - checks[type].receive = true; - checks[type].correct = result; - console.error('check', checks); - - var missing = false; - forEach(checks, function(type) { - if (type.receive === false) missing = true; - }); - - if (missing === false) { - console.error('end client'); - client.end(); - } - }; - - // Spawn worker - var worker = cluster.fork(); - - // When a IPC message is received form the worker - worker.on('message', function(message) { - check('master', message === 'message from worker'); - }); - - // When a TCP connection is made with the worker connect to it - worker.on('listening', function() { - - client = net.connect(common.PORT, function() { - // Send message to worker. - worker.send('message from master'); - }); - - client.on('data', function(data) { - // All data is JSON - data = JSON.parse(data.toString()); - - if (data.code === 'received message') { - check('worker', data.echo === 'message from master'); - } else { - throw new Error('wrong TCP message recived: ' + data); - } - }); - - // When the connection ends kill worker and shutdown process - client.on('end', function() { - worker.kill(); - }); - - worker.on('exit', function() { - process.exit(0); - }); - }); - - process.once('exit', function() { - forEach(checks, function(check, type) { - assert.ok(check.receive, 'The ' + type + ' did not receive any message'); - assert.ok(check.correct, - 'The ' + type + ' did not get the correct message'); - }); - }); -} diff --git a/test/simple/test-cluster-net-listen.js b/test/simple/test-cluster-net-listen.js deleted file mode 100644 index 927169c72..000000000 --- a/test/simple/test-cluster-net-listen.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (cluster.isMaster) { - // ensure that the worker exits peacefully - var worker = cluster.fork(); - worker.on('exit', function(statusCode) { - assert.equal(statusCode, 0); - worker = null; - }); - process.on('exit', function() { - assert.equal(worker, null); - }); -} -else { - // listen() without port should not trigger a libuv assert - net.createServer(assert.fail).listen(process.exit); -} diff --git a/test/simple/test-cluster-net-send.js b/test/simple/test-cluster-net-send.js deleted file mode 100644 index 1313a624a..000000000 --- a/test/simple/test-cluster-net-send.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fork = require('child_process').fork; -var net = require('net'); - -if (process.argv[2] !== 'child') { - console.error('[%d] master', process.pid); - - var worker = fork(__filename, ['child']); - var called = false; - - worker.once('message', function(msg, handle) { - assert.equal(msg, 'handle'); - assert.ok(handle); - worker.send('got'); - - handle.on('data', function(data) { - called = true; - assert.equal(data.toString(), 'hello'); - }); - - handle.on('end', function() { - worker.kill(); - }); - }); - - process.once('exit', function() { - assert.ok(called); - }); -} else { - console.error('[%d] worker', process.pid); - - var server = net.createServer(function(c) { - process.once('message', function(msg) { - assert.equal(msg, 'got'); - c.end('hello'); - }); - }); - server.listen(common.PORT, function() { - var socket = net.connect(common.PORT, '127.0.0.1', function() { - process.send('handle', socket); - }); - }); - - process.on('disconnect', function() { - process.exit(); - server.close(); - }); -} diff --git a/test/simple/test-cluster-rr-domain-listen.js b/test/simple/test-cluster-rr-domain-listen.js deleted file mode 100755 index 574036df2..000000000 --- a/test/simple/test-cluster-rr-domain-listen.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var cluster = require('cluster'); -var domain = require('domain'); - -// RR is the default for v0.11.9+ so the following line is redundant: -// cluster.schedulingPolicy = cluster.SCHED_RR; - -if (cluster.isWorker) { - var d = domain.create(); - d.run(function () { }); - - var http = require('http'); - http.Server(function() { }).listen(common.PORT, '127.0.0.1'); - -} else if (cluster.isMaster) { - var worker; - - //Kill worker when listening - cluster.on('listening', function() { - worker.kill(); - }); - - //Kill process when worker is killed - cluster.on('exit', function() { - process.exit(0); - }); - - //Create worker - worker = cluster.fork(); -} diff --git a/test/simple/test-cluster-send-deadlock.js b/test/simple/test-cluster-send-deadlock.js deleted file mode 100644 index 1b4a90dee..000000000 --- a/test/simple/test-cluster-send-deadlock.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Testing mutual send of handles: from master to worker, and from worker to -// master. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (cluster.isMaster) { - var worker = cluster.fork(); - worker.on('exit', function(code, signal) { - assert.equal(code, 0, 'Worker exited with an error code'); - assert(!signal, 'Worker exited by a signal'); - server.close(); - }); - - var server = net.createServer(function(socket) { - worker.send('handle', socket); - }); - - server.listen(common.PORT, function() { - worker.send('listen'); - }); -} else { - process.on('message', function(msg, handle) { - if (msg === 'listen') { - var client1 = net.connect({ host: 'localhost', port: common.PORT }); - var client2 = net.connect({ host: 'localhost', port: common.PORT }); - var waiting = 2; - client1.on('close', onclose); - client2.on('close', onclose); - function onclose() { - if (--waiting === 0) - cluster.worker.disconnect(); - } - setTimeout(function() { - client1.end(); - client2.end(); - }, 50); - } else { - process.send('reply', handle); - } - }); -} diff --git a/test/simple/test-cluster-send-handle-twice.js b/test/simple/test-cluster-send-handle-twice.js deleted file mode 100644 index 3215eae79..000000000 --- a/test/simple/test-cluster-send-handle-twice.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Testing to send an handle twice to the parent process. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -var workers = { - toStart: 1 -}; - -if (cluster.isMaster) { - for (var i = 0; i < workers.toStart; ++i) { - var worker = cluster.fork(); - worker.on('exit', function(code, signal) { - assert.equal(code, 0, 'Worker exited with an error code'); - assert(!signal, 'Worker exited by a signal'); - }); - } -} else { - var server = net.createServer(function(socket) { - process.send('send-handle-1', socket); - process.send('send-handle-2', socket); - }); - - server.listen(common.PORT, function() { - var client = net.connect({ host: 'localhost', port: common.PORT }); - client.on('close', function() { cluster.worker.disconnect(); }); - setTimeout(function() { client.end(); }, 50); - }).on('error', function(e) { - console.error(e); - assert(false, 'server.listen failed'); - cluster.worker.disconnect(); - }); -} diff --git a/test/simple/test-cluster-setup-master-argv.js b/test/simple/test-cluster-setup-master-argv.js deleted file mode 100644 index d216943c8..000000000 --- a/test/simple/test-cluster-setup-master-argv.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -setTimeout(assert.fail.bind(assert, 'setup not emitted'), 1000).unref(); - -cluster.on('setup', function() { - var clusterArgs = cluster.settings.args; - var realArgs = process.argv; - assert.equal(clusterArgs[clusterArgs.length - 1], - realArgs[realArgs.length - 1]); -}); - -assert(process.argv[process.argv.length - 1] !== 'OMG,OMG'); -process.argv.push('OMG,OMG'); -process.argv.push('OMG,OMG'); -cluster.setupMaster(); diff --git a/test/simple/test-cluster-setup-master-cumulative.js b/test/simple/test-cluster-setup-master-cumulative.js deleted file mode 100644 index 2f69cd368..000000000 --- a/test/simple/test-cluster-setup-master-cumulative.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -assert(cluster.isMaster); - -assert.deepEqual(cluster.settings, {}, - 'cluster.settings should not be initialized until needed'); - -cluster.setupMaster(); -assert.deepEqual(cluster.settings, { - args: process.argv.slice(2), - exec: process.argv[1], - execArgv: process.execArgv, - silent: false, -}); -console.log('ok sets defaults'); - -cluster.setupMaster({ exec: 'overridden' }); -assert.strictEqual(cluster.settings.exec, 'overridden'); -console.log('ok overrids defaults'); - -cluster.setupMaster({ args: ['foo', 'bar'] }); -assert.strictEqual(cluster.settings.exec, 'overridden'); -assert.deepEqual(cluster.settings.args, ['foo', 'bar']); - -cluster.setupMaster({ execArgv: ['baz', 'bang'] }); -assert.strictEqual(cluster.settings.exec, 'overridden'); -assert.deepEqual(cluster.settings.args, ['foo', 'bar']); -assert.deepEqual(cluster.settings.execArgv, ['baz', 'bang']); -console.log('ok preserves unchanged settings on repeated calls'); - -cluster.setupMaster(); -assert.deepEqual(cluster.settings, { - args: ['foo', 'bar'], - exec: 'overridden', - execArgv: ['baz', 'bang'], - silent: false, -}); -console.log('ok preserves current settings'); diff --git a/test/simple/test-cluster-setup-master-emit.js b/test/simple/test-cluster-setup-master-emit.js deleted file mode 100644 index ee3af2ad4..000000000 --- a/test/simple/test-cluster-setup-master-emit.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -assert(cluster.isMaster); - -var assertsRun = 0; - -function emitAndCatch(next) { - cluster.once('setup', function(settings) { - assert.strictEqual(settings.exec, 'new-exec'); - console.log('ok "setup" emitted with options set'); - assertsRun += 1; - setImmediate(next); - }); - cluster.setupMaster({ exec: 'new-exec' }); -} - -function emitAndCatch2(next) { - cluster.once('setup', function(settings) { - assert('exec' in settings); - console.log('ok "setup" emitted without options set'); - assertsRun += 1; - setImmediate(next); - }); - cluster.setupMaster(); -} - -process.on('exit', function() { - assert.strictEqual(assertsRun, 2); - console.log('ok correct number of assertions'); -}); - -emitAndCatch(function() { - emitAndCatch2(function() { - console.log('ok emitted and caught'); - }); -}); diff --git a/test/simple/test-cluster-setup-master-multiple.js b/test/simple/test-cluster-setup-master-multiple.js deleted file mode 100644 index 21756b9c0..000000000 --- a/test/simple/test-cluster-setup-master-multiple.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -assert(cluster.isMaster); - -// The cluster.settings object is cloned even though the current implementation -// makes that unecessary. This is to make the test less fragile if the -// implementation ever changes such that cluster.settings is mutated instead of -// replaced. -function cheapClone(obj) { - return JSON.parse(JSON.stringify(obj)); -} - -var configs = []; - -// Capture changes -cluster.on('setup', function() { - console.log('"setup" emitted', cluster.settings); - configs.push(cheapClone(cluster.settings)); -}); - -var execs = [ - 'node-next', - 'node-next-2', - 'node-next-3', -]; - -process.on('exit', function assertTests() { - // Tests that "setup" is emitted for every call to setupMaster - assert.strictEqual(configs.length, execs.length); - - assert.strictEqual(configs[0].exec, execs[0]); - assert.strictEqual(configs[1].exec, execs[1]); - assert.strictEqual(configs[2].exec, execs[2]); -}); - -// Make changes to cluster settings -execs.forEach(function(v, i) { - setTimeout(function() { - cluster.setupMaster({ exec: v }); - }, i * 100); -}); - -// cluster emits 'setup' asynchronously, so we must stay alive long -// enough for that to happen -setTimeout(function() { - console.log('cluster setup complete'); -}, (execs.length + 1) * 100); diff --git a/test/simple/test-cluster-setup-master.js b/test/simple/test-cluster-setup-master.js deleted file mode 100644 index d9f387928..000000000 --- a/test/simple/test-cluster-setup-master.js +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (cluster.isWorker) { - - // Just keep the worker alive - process.send(process.argv[2]); - -} else if (cluster.isMaster) { - - var checks = { - args: false, - setupEvent: false, - settingsObject: false - }; - - var totalWorkers = 2; - - // Setup master - cluster.setupMaster({ - args: ['custom argument'], - silent: true - }); - - cluster.once('setup', function() { - checks.setupEvent = true; - - var settings = cluster.settings; - if (settings && - settings.args && settings.args[0] === 'custom argument' && - settings.silent === true && - settings.exec === process.argv[1]) { - checks.settingsObject = true; - } - }); - - var correctIn = 0; - - cluster.on('online', function lisenter(worker) { - - worker.once('message', function(data) { - correctIn += (data === 'custom argument' ? 1 : 0); - if (correctIn === totalWorkers) { - checks.args = true; - } - worker.kill(); - }); - - // All workers are online - if (cluster.onlineWorkers === totalWorkers) { - checks.workers = true; - } - }); - - // Start all workers - cluster.fork(); - cluster.fork(); - - // Check all values - process.once('exit', function() { - assert.ok(checks.args, 'The arguments was noy send to the worker'); - assert.ok(checks.setupEvent, 'The setup event was never emitted'); - var m = 'The settingsObject do not have correct properties'; - assert.ok(checks.settingsObject, m); - }); - -} diff --git a/test/simple/test-cluster-shared-handle-bind-error.js b/test/simple/test-cluster-shared-handle-bind-error.js deleted file mode 100644 index ceccd9146..000000000 --- a/test/simple/test-cluster-shared-handle-bind-error.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (cluster.isMaster) { - // Master opens and binds the socket and shares it with the worker. - cluster.schedulingPolicy = cluster.SCHED_NONE; - // Hog the TCP port so that when the worker tries to bind, it'll fail. - net.createServer(assert.fail).listen(common.PORT, function() { - var server = this; - var worker = cluster.fork(); - worker.on('exit', common.mustCall(function(exitCode) { - assert.equal(exitCode, 0); - server.close(); - })); - }); -} -else { - var s = net.createServer(assert.fail); - s.listen(common.PORT, assert.fail.bind(null, 'listen should have failed')); - s.on('error', common.mustCall(function(err) { - assert.equal(err.code, 'EADDRINUSE'); - process.disconnect(); - })); -} diff --git a/test/simple/test-cluster-shared-handle-bind-privileged-port.js b/test/simple/test-cluster-shared-handle-bind-privileged-port.js deleted file mode 100644 index 67b3a8840..000000000 --- a/test/simple/test-cluster-shared-handle-bind-privileged-port.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -if (process.platform === 'win32') { - console.log('Skipping test, not reliable on Windows.'); - process.exit(0); -} - -if (process.getuid() === 0) { - console.log('Do not run this test as root.'); - process.exit(0); -} - -if (cluster.isMaster) { - // Master opens and binds the socket and shares it with the worker. - cluster.schedulingPolicy = cluster.SCHED_NONE; - cluster.fork().on('exit', common.mustCall(function(exitCode) { - assert.equal(exitCode, 0); - })); -} -else { - var s = net.createServer(assert.fail); - s.listen(42, assert.fail.bind(null, 'listen should have failed')); - s.on('error', common.mustCall(function(err) { - assert.equal(err.code, 'EACCES'); - process.disconnect(); - })); -} diff --git a/test/simple/test-cluster-uncaught-exception.js b/test/simple/test-cluster-uncaught-exception.js deleted file mode 100644 index 48a825127..000000000 --- a/test/simple/test-cluster-uncaught-exception.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Installing a custom uncaughtException handler should override the default -// one that the cluster module installs. -// https://github.com/joyent/node/issues/2556 - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var fork = require('child_process').fork; - -var MAGIC_EXIT_CODE = 42; - -var isTestRunner = process.argv[2] != 'child'; - -if (isTestRunner) { - var exitCode = -1; - - process.on('exit', function() { - assert.equal(exitCode, MAGIC_EXIT_CODE); - }); - - var master = fork(__filename, ['child']); - master.on('exit', function(code) { - exitCode = code; - }); -} -else if (cluster.isMaster) { - process.on('uncaughtException', function() { - process.nextTick(function() { - process.exit(MAGIC_EXIT_CODE); - }); - }); - - cluster.fork(); - throw new Error('kill master'); -} -else { // worker - process.exit(); -} diff --git a/test/simple/test-cluster-worker-constructor.js b/test/simple/test-cluster-worker-constructor.js deleted file mode 100644 index ce7945cdb..000000000 --- a/test/simple/test-cluster-worker-constructor.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// test-cluster-worker-constructor.js -// validates correct behavior of the cluster.Worker constructor - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var worker; - -worker = new cluster.Worker(); -assert.equal(worker.suicide, undefined); -assert.equal(worker.state, 'none'); -assert.equal(worker.id, 0); -assert.equal(worker.process, undefined); - -worker = new cluster.Worker({ - id: 3, - state: 'online', - process: process -}); -assert.equal(worker.suicide, undefined); -assert.equal(worker.state, 'online'); -assert.equal(worker.id, 3); -assert.equal(worker.process, process); - -worker = cluster.Worker.call({}, {id: 5}); -assert(worker instanceof cluster.Worker); -assert.equal(worker.id, 5); diff --git a/test/simple/test-cluster-worker-death.js b/test/simple/test-cluster-worker-death.js deleted file mode 100644 index ccd48552a..000000000 --- a/test/simple/test-cluster-worker-death.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (!cluster.isMaster) { - process.exit(42); -} -else { - var seenExit = 0; - var seenDeath = 0; - var worker = cluster.fork(); - worker.on('exit', function(exitCode, signalCode) { - assert.equal(exitCode, 42); - assert.equal(signalCode, null); - seenExit++; - }); - cluster.on('exit', function(worker_) { - assert.equal(worker_, worker); - seenDeath++; - }); - process.on('exit', function() { - assert.equal(seenExit, 1); - assert.equal(seenDeath, 1); - }); -} diff --git a/test/simple/test-cluster-worker-destroy.js b/test/simple/test-cluster-worker-destroy.js deleted file mode 100644 index 318b55caf..000000000 --- a/test/simple/test-cluster-worker-destroy.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * The goal of this test is to cover the Workers' implementation of - * Worker.prototype.destroy. Worker.prototype.destroy is called within - * the worker's context: once when the worker is still connected to the - * master, and another time when it's not connected to it, so that we cover - * both code paths. - */ - -require('../common'); -var cluster = require('cluster'); -var assert = require('assert'); - -var worker1, worker2, workerExited, workerDisconnected; - -if (cluster.isMaster) { - worker1 = cluster.fork(); - worker2 = cluster.fork(); - - workerExited = 0; - workerDisconnected = 0; - - [worker1, worker2].forEach(function(worker) { - worker.on('disconnect', ondisconnect); - worker.on('exit', onexit); - }); - - process.on('exit', onProcessExit); - -} else { - if (cluster.worker.id === 1) { - // Call destroy when worker is disconnected - cluster.worker.process.on('disconnect', function() { - cluster.worker.destroy(); - }); - - cluster.worker.disconnect(); - } else { - // Call destroy when worker is not disconnected yet - cluster.worker.destroy(); - } -} - -function onProcessExit() { - assert.equal(workerExited, - 2, - 'When master exits, all workers should have exited too'); - assert.equal(workerDisconnected, - 2, - 'When master exits, all workers should have disconnected'); -} - -function ondisconnect() { - ++workerDisconnected; -} - -function onexit() { - ++workerExited; -} diff --git a/test/simple/test-cluster-worker-disconnect.js b/test/simple/test-cluster-worker-disconnect.js deleted file mode 100644 index 632a25f2d..000000000 --- a/test/simple/test-cluster-worker-disconnect.js +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (cluster.isWorker) { - var http = require('http'); - http.Server(function() { - - }).listen(common.PORT, '127.0.0.1'); - -} else if (cluster.isMaster) { - - var checks = { - cluster: { - emitDisconnect: false, - emitExit: false, - callback: false - }, - worker: { - emitDisconnect: false, - emitExit: false, - state: false, - suicideMode: false, - died: false - } - }; - - // helper function to check if a process is alive - var alive = function(pid) { - try { - process.kill(pid, 0); - return true; - } catch (e) { - return false; - } - }; - - // start worker - var worker = cluster.fork(); - - // Disconnect worker when it is ready - worker.once('listening', function() { - worker.disconnect(); - }); - - // Check cluster events - cluster.once('disconnect', function() { - checks.cluster.emitDisconnect = true; - }); - cluster.once('exit', function() { - checks.cluster.emitExit = true; - }); - - // Check worker events and properties - worker.once('disconnect', function() { - checks.worker.emitDisconnect = true; - checks.worker.suicideMode = worker.suicide; - checks.worker.state = worker.state; - }); - - // Check that the worker died - worker.once('exit', function() { - checks.worker.emitExit = true; - checks.worker.died = !alive(worker.process.pid); - process.nextTick(function() { - process.exit(0); - }); - }); - - process.once('exit', function() { - - var w = checks.worker; - var c = checks.cluster; - - // events - assert.ok(w.emitDisconnect, 'Disconnect event did not emit'); - assert.ok(c.emitDisconnect, 'Disconnect event did not emit'); - assert.ok(w.emitExit, 'Exit event did not emit'); - assert.ok(c.emitExit, 'Exit event did not emit'); - - // flags - assert.equal(w.state, 'disconnected', 'The state property was not set'); - assert.equal(w.suicideMode, true, 'Suicide mode was not set'); - - // is process alive - assert.ok(w.died, 'The worker did not die'); - }); -} diff --git a/test/simple/test-cluster-worker-events.js b/test/simple/test-cluster-worker-events.js deleted file mode 100644 index 1276650d1..000000000 --- a/test/simple/test-cluster-worker-events.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var assert = require('assert'); -var cluster = require('cluster'); - -var OK = 2; - -if (cluster.isMaster) { - - var worker = cluster.fork(); - - worker.on('exit', function(code) { - assert.equal(code, OK); - process.exit(0); - }); - - worker.send('SOME MESSAGE'); - - return; -} - -// Messages sent to a worker will be emitted on both the process object and the -// process.worker object. - -assert(cluster.isWorker); - -var sawProcess; -var sawWorker; - -process.on('message', function(m) { - assert(!sawProcess); - sawProcess = true; - check(m); -}); - -cluster.worker.on('message', function(m) { - assert(!sawWorker); - sawWorker = true; - check(m); -}); - -var messages = []; - -function check(m) { - messages.push(m); - - if (messages.length < 2) return; - - assert.deepEqual(messages[0], messages[1]); - - cluster.worker.once('error', function(e) { - assert.equal(e, 'HI'); - process.exit(OK); - }); - - process.emit('error', 'HI'); -} diff --git a/test/simple/test-cluster-worker-exit.js b/test/simple/test-cluster-worker-exit.js deleted file mode 100644 index 7b9d5d86c..000000000 --- a/test/simple/test-cluster-worker-exit.js +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// test-cluster-worker-exit.js -// verifies that, when a child process exits (by calling `process.exit(code)`) -// - the parent receives the proper events in the proper order, no duplicates -// - the exitCode and signalCode are correct in the 'exit' event -// - the worker.suicide flag, and worker.state are correct -// - the worker process actually goes away - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -var EXIT_CODE = 42; - -if (cluster.isWorker) { - var http = require('http'); - var server = http.Server(function() { }); - - server.once('listening', function() { - process.exit(EXIT_CODE); - }); - server.listen(common.PORT, '127.0.0.1'); - -} else if (cluster.isMaster) { - - var expected_results = { - cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], - cluster_emitExit: [1, "the cluster did not emit 'exit'"], - cluster_exitCode: [EXIT_CODE, 'the cluster exited w/ incorrect exitCode'], - cluster_signalCode: [null, 'the cluster exited w/ incorrect signalCode'], - worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], - worker_emitExit: [1, "the worker did not emit 'exit'"], - worker_state: ['disconnected', 'the worker state is incorrect'], - worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], - worker_died: [true, 'the worker is still running'], - worker_exitCode: [EXIT_CODE, 'the worker exited w/ incorrect exitCode'], - worker_signalCode: [null, 'the worker exited w/ incorrect signalCode'] - }; - var results = { - cluster_emitDisconnect: 0, - cluster_emitExit: 0, - worker_emitDisconnect: 0, - worker_emitExit: 0 - }; - - - // start worker - var worker = cluster.fork(); - - worker.once('listening', function() { - // the worker is up and running... - }); - - - // Check cluster events - cluster.on('disconnect', function() { - results.cluster_emitDisconnect += 1; - }); - cluster.on('exit', function(worker) { - results.cluster_exitCode = worker.process.exitCode; - results.cluster_signalCode = worker.process.signalCode; - results.cluster_emitExit += 1; - assert.ok(results.cluster_emitDisconnect, - "cluster: 'exit' event before 'disconnect' event"); - }); - - // Check worker events and properties - worker.on('disconnect', function() { - results.worker_emitDisconnect += 1; - results.worker_suicideMode = worker.suicide; - results.worker_state = worker.state; - }); - - // Check that the worker died - worker.once('exit', function(exitCode, signalCode) { - results.worker_exitCode = exitCode; - results.worker_signalCode = signalCode; - results.worker_emitExit += 1; - results.worker_died = !alive(worker.process.pid); - assert.ok(results.worker_emitDisconnect, - "worker: 'exit' event before 'disconnect' event"); - - process.nextTick(function() { finish_test(); }); - }); - - var finish_test = function() { - try { - checkResults(expected_results, results); - } catch (exc) { - console.error('FAIL: ' + exc.message); - if (exc.name != 'AssertionError') { - console.trace(exc); - } - - process.exit(1); - return; - } - process.exit(0); - }; -} - -// some helper functions ... - - function checkResults(expected_results, results) { - for (var k in expected_results) { - var actual = results[k], - expected = expected_results[k]; - - if (typeof expected === 'function') { - expected(r[k]); - } else { - var msg = (expected[1] || '') + - (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); - - if (expected && expected.length) { - assert.equal(actual, expected[0], msg); - } else { - assert.equal(actual, expected, msg); - } - } - } - } - - function alive(pid) { - try { - process.kill(pid, 'SIGCONT'); - return true; - } catch (e) { - return false; - } - } diff --git a/test/simple/test-cluster-worker-forced-exit.js b/test/simple/test-cluster-worker-forced-exit.js deleted file mode 100644 index 66d5f1835..000000000 --- a/test/simple/test-cluster-worker-forced-exit.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var cluster = require('cluster') -var net = require('net'); - -var SENTINEL = 42; - -// workers forcibly exit when control channel is disconnected, if -// their .suicide flag isn't set -// -// test this by: -// -// 1 setup worker to wait a short time after disconnect, and exit -// with a sentinel value -// 2 disconnect worker with cluster's disconnect, confirm sentinel -// 3 disconnect worker with child_process's disconnect, confirm -// no sentinel value -if (cluster.isWorker) { - process.on('disconnect', function(msg) { - setTimeout(function() { - process.exit(SENTINEL); - }, 10); - }); - return; -} - -var unforcedOk; -var forcedOk; - -process.on('exit', function() { - assert(forcedOk); - assert(unforcedOk); -}); - -checkUnforced(); -checkForced(); - -function checkUnforced() { - cluster.fork() - .on('online', function() { - this.disconnect(); - }) - .on('exit', function(status) { - assert.equal(status, SENTINEL); - unforcedOk = true; - }); -} - -function checkForced() { - cluster.fork() - .on('online', function() { - this.process.disconnect(); - }) - .on('exit', function(status) { - assert.equal(status, 0); - forcedOk = true; - }); -} diff --git a/test/simple/test-cluster-worker-init.js b/test/simple/test-cluster-worker-init.js deleted file mode 100644 index f750262e8..000000000 --- a/test/simple/test-cluster-worker-init.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// test-cluster-worker-init.js -// verifies that, when a child process is forked, the cluster.worker -// object can receive messages as expected - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var msg = 'foo'; - -if (cluster.isMaster) { - var worker = cluster.fork(); - var timer = setTimeout(function() { - assert(false, 'message not received'); - }, 5000); - - timer.unref(); - - worker.on('message', function(message) { - assert(message, 'did not receive expected message'); - worker.disconnect(); - }); - - worker.on('online', function() { - worker.send(msg); - }); -} else { - // GH #7998 - cluster.worker.on('message', function(message) { - process.send(message === msg); - }); -} diff --git a/test/simple/test-cluster-worker-isconnected.js b/test/simple/test-cluster-worker-isconnected.js deleted file mode 100644 index ed839d496..000000000 --- a/test/simple/test-cluster-worker-isconnected.js +++ /dev/null @@ -1,37 +0,0 @@ -var cluster = require('cluster'); -var assert = require('assert'); -var util = require('util'); - -if (cluster.isMaster) { - var worker = cluster.fork(); - - assert.ok(worker.isConnected(), - "isConnected() should return true as soon as the worker has " + - "been created."); - - worker.on('disconnect', function() { - assert.ok(!worker.isConnected(), - "After a disconnect event has been emitted, " + - "isConncted should return false"); - }); - - worker.on('message', function(msg) { - if (msg === 'readyToDisconnect') { - worker.disconnect(); - } - }) - -} else { - assert.ok(cluster.worker.isConnected(), - "isConnected() should return true from within a worker at all " + - "times."); - - cluster.worker.process.on('disconnect', function() { - assert.ok(!cluster.worker.isConnected(), - "isConnected() should return false from within a worker " + - "after its underlying process has been disconnected from " + - "the master"); - }) - - process.send('readyToDisconnect'); -} diff --git a/test/simple/test-cluster-worker-isdead.js b/test/simple/test-cluster-worker-isdead.js deleted file mode 100644 index 11766c597..000000000 --- a/test/simple/test-cluster-worker-isdead.js +++ /dev/null @@ -1,27 +0,0 @@ -var cluster = require('cluster'); -var assert = require('assert'); -var net = require('net'); - -if (cluster.isMaster) { - var worker = cluster.fork(); - assert.ok(!worker.isDead(), - "isDead() should return false right after the worker has been " + - "created."); - - worker.on('exit', function() { - assert.ok(!worker.isConnected(), - "After an event has been emitted, " + - "isDead should return true"); - }) - - worker.on('message', function(msg) { - if (msg === 'readyToDie') { - worker.kill(); - } - }); - -} else if (cluster.isWorker) { - assert.ok(!cluster.worker.isDead(), - "isDead() should return false when called from within a worker"); - process.send('readyToDie'); -} diff --git a/test/simple/test-cluster-worker-kill.js b/test/simple/test-cluster-worker-kill.js deleted file mode 100644 index 8c6068e8d..000000000 --- a/test/simple/test-cluster-worker-kill.js +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// test-cluster-worker-kill.js -// verifies that, when a child process is killed (we use SIGKILL) -// - the parent receives the proper events in the proper order, no duplicates -// - the exitCode and signalCode are correct in the 'exit' event -// - the worker.suicide flag, and worker.state are correct -// - the worker process actually goes away - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); - -if (cluster.isWorker) { - var http = require('http'); - var server = http.Server(function() { }); - - server.once('listening', function() { }); - server.listen(common.PORT, '127.0.0.1'); - -} else if (cluster.isMaster) { - - var KILL_SIGNAL = 'SIGKILL', - expected_results = { - cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], - cluster_emitExit: [1, "the cluster did not emit 'exit'"], - cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], - cluster_signalCode: [KILL_SIGNAL, 'the cluster exited w/ incorrect signalCode'], - worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], - worker_emitExit: [1, "the worker did not emit 'exit'"], - worker_state: ['disconnected', 'the worker state is incorrect'], - worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], - worker_died: [true, 'the worker is still running'], - worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], - worker_signalCode: [KILL_SIGNAL, 'the worker exited w/ incorrect signalCode'] - }, - results = { - cluster_emitDisconnect: 0, - cluster_emitExit: 0, - worker_emitDisconnect: 0, - worker_emitExit: 0 - }; - - - // start worker - var worker = cluster.fork(); - - // when the worker is up and running, kill it - worker.once('listening', function() { - worker.process.kill(KILL_SIGNAL); - }); - - - // Check cluster events - cluster.on('disconnect', function() { - results.cluster_emitDisconnect += 1; - }); - cluster.on('exit', function(worker) { - results.cluster_exitCode = worker.process.exitCode; - results.cluster_signalCode = worker.process.signalCode; - results.cluster_emitExit += 1; - assert.ok(results.cluster_emitDisconnect, - "cluster: 'exit' event before 'disconnect' event"); - }); - - // Check worker events and properties - worker.on('disconnect', function() { - results.worker_emitDisconnect += 1; - results.worker_suicideMode = worker.suicide; - results.worker_state = worker.state; - }); - - // Check that the worker died - worker.once('exit', function(exitCode, signalCode) { - results.worker_exitCode = exitCode; - results.worker_signalCode = signalCode; - results.worker_emitExit += 1; - results.worker_died = !alive(worker.process.pid); - assert.ok(results.worker_emitDisconnect, - "worker: 'exit' event before 'disconnect' event"); - - process.nextTick(function() { finish_test(); }); - }); - - var finish_test = function() { - try { - checkResults(expected_results, results); - } catch (exc) { - console.error('FAIL: ' + exc.message); - if (exc.name != 'AssertionError') { - console.trace(exc); - } - - process.exit(1); - return; - } - process.exit(0); - }; -} - -// some helper functions ... - - function checkResults(expected_results, results) { - for (var k in expected_results) { - var actual = results[k], - expected = expected_results[k]; - - if (typeof expected === 'function') { - expected(r[k]); - } else { - var msg = (expected[1] || '') + - (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); - if (expected && expected.length) { - assert.equal(actual, expected[0], msg); - } else { - assert.equal(actual, expected, msg); - } - } - } - } - - function alive(pid) { - try { - process.kill(pid, 'SIGCONT'); - return true; - } catch (e) { - return false; - } - } diff --git a/test/simple/test-cluster-worker-no-exit.js b/test/simple/test-cluster-worker-no-exit.js deleted file mode 100644 index c521fcbb1..000000000 --- a/test/simple/test-cluster-worker-no-exit.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var cluster = require('cluster') -var net = require('net'); - -var destroyed; -var success; -var worker; -var server; - -// workers do not exit on disconnect, they exit under normal node rules: when -// they have nothing keeping their loop alive, like an active connection -// -// test this by: -// -// 1 creating a server, so worker can make a connection to something -// 2 disconnecting worker -// 3 wait to confirm it did not exit -// 4 destroy connection -// 5 confirm it does exit -if (cluster.isMaster) { - server = net.createServer(function(conn) { - server.close(); - worker.disconnect() - worker.once('disconnect', function() { - setTimeout(function() { - conn.destroy(); - destroyed = true; - }, 1000); - }).once('exit', function() { - // worker should not exit while it has a connection - assert(destroyed, 'worker exited before connection destroyed'); - success = true; - }); - - }).listen(0, function() { - var port = this.address().port; - - worker = cluster.fork() - .on('online', function() { - this.send({port: port}); - }); - }); - process.on('exit', function() { - assert(success); - }); -} else { - process.on('message', function(msg) { - // we shouldn't exit, not while a network connection exists - net.connect(msg.port); - }); -} diff --git a/test/simple/test-common.js b/test/simple/test-common.js deleted file mode 100644 index 420bd52a0..000000000 --- a/test/simple/test-common.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -common.globalCheck = false; -global.gc = 42; // Not a valid global unless --expose_gc is set. -assert.deepEqual(common.leakedGlobals(), ['gc']); diff --git a/test/simple/test-console-instance.js b/test/simple/test-console-instance.js deleted file mode 100644 index e0166ebd3..000000000 --- a/test/simple/test-console-instance.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var Stream = require('stream'); -var Console = require('console').Console; -var called = false; - -// ensure the Console instance doesn't write to the -// process' "stdout" or "stderr" streams -process.stdout.write = process.stderr.write = function() { - throw new Error('write() should not be called!'); -}; - -// make sure that the "Console" function exists -assert.equal('function', typeof Console); - -// make sure that the Console constructor throws -// when not given a writable stream instance -assert.throws(function () { - new Console(); -}, /Console expects a writable stream/); - -var out = new Stream(); -var err = new Stream(); -out.writable = err.writable = true; -out.write = err.write = function(d) {}; - -var c = new Console(out, err); - -out.write = err.write = function(d) { - assert.equal(d, 'test\n'); - called = true; -}; - -assert(!called); -c.log('test'); -assert(called); - -called = false; -c.error('test'); -assert(called); - -out.write = function(d) { - assert.equal('{ foo: 1 }\n', d); - called = true; -}; - -called = false; -c.dir({ foo: 1 }); -assert(called); - -// ensure that the console functions are bound to the console instance -called = 0; -out.write = function(d) { - called++; - assert.equal(d, called + ' ' + (called - 1) + ' [ 1, 2, 3 ]\n'); -}; -[1, 2, 3].forEach(c.log); -assert.equal(3, called); diff --git a/test/simple/test-console-not-call-toString.js b/test/simple/test-console-not-call-toString.js deleted file mode 100644 index a62004f70..000000000 --- a/test/simple/test-console-not-call-toString.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var func = function() {}; -var toStringCalled = false; -func.toString = function() { - toStringCalled = true; -}; - -require('util').inspect(func); - -assert.ok(!toStringCalled); diff --git a/test/simple/test-console.js b/test/simple/test-console.js deleted file mode 100644 index 14ece8af5..000000000 --- a/test/simple/test-console.js +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -assert.ok(process.stdout.writable); -assert.ok(process.stderr.writable); -// Support legacy API -assert.equal('number', typeof process.stdout.fd); -assert.equal('number', typeof process.stderr.fd); - -// an Object with a custom .inspect() function -var custom_inspect = { foo: 'bar', inspect: function () { return 'inspect'; } }; - -var stdout_write = global.process.stdout.write; -var strings = []; -global.process.stdout.write = function(string) { - strings.push(string); -}; -console._stderr = process.stdout; - -// test console.log() -console.log('foo'); -console.log('foo', 'bar'); -console.log('%s %s', 'foo', 'bar', 'hop'); -console.log({slashes: '\\\\'}); -console.log(custom_inspect); - -// test console.dir() -console.dir(custom_inspect); -console.dir(custom_inspect, { showHidden: false }); -console.dir({ foo : { bar : { baz : true } } }, { depth: 0 }); -console.dir({ foo : { bar : { baz : true } } }, { depth: 1 }); - -// test console.trace() -console.trace('This is a %j %d', { formatted: 'trace' }, 10, 'foo'); - - -global.process.stdout.write = stdout_write; - -assert.equal('foo\n', strings.shift()); -assert.equal('foo bar\n', strings.shift()); -assert.equal('foo bar hop\n', strings.shift()); -assert.equal("{ slashes: '\\\\\\\\' }\n", strings.shift()); -assert.equal('inspect\n', strings.shift()); -assert.equal("{ foo: 'bar', inspect: [Function] }\n", strings.shift()); -assert.equal("{ foo: 'bar', inspect: [Function] }\n", strings.shift()); -assert.notEqual(-1, strings.shift().indexOf('foo: [Object]')); -assert.equal(-1, strings.shift().indexOf('baz')); -assert.equal('Trace: This is a {"formatted":"trace"} 10 foo', - strings.shift().split('\n').shift()); - -assert.throws(function () { - console.timeEnd('no such label'); -}); - -assert.doesNotThrow(function () { - console.time('label'); - console.timeEnd('label'); -}); diff --git a/test/simple/test-crypto-authenticated.js b/test/simple/test-crypto-authenticated.js deleted file mode 100644 index 8b4411607..000000000 --- a/test/simple/test-crypto-authenticated.js +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - -// -// Test authenticated encryption modes. -// -// !NEVER USE STATIC IVs IN REAL LIFE! -// - -var TEST_CASES = [ - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', - iv: '583673497131313748307652', plain: 'Hello World!', - ct: '4BE13896F64DFA2C2D0F2C76', - tag: '272B422F62EB545EAA15B5FF84092447', tampered: false }, - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', - iv: '583673497131313748307652', plain: 'Hello World!', - ct: '4BE13896F64DFA2C2D0F2C76', aad: '000000FF', - tag: 'BA2479F66275665A88CB7B15F43EB005', tampered: false }, - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', - iv: '583673497131313748307652', plain: 'Hello World!', - ct: '4BE13596F64DFA2C2D0FAC76', - tag: '272B422F62EB545EAA15B5FF84092447', tampered: true }, - { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', - iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', - ct: '58E62CFE7B1D274111A82267EBB93866E72B6C2A', - tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: false }, - { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', - iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', - ct: '58E62CFF7B1D274011A82267EBB93866E72B6C2B', - tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: true }, - { algo: 'aes-192-gcm', key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', - iv: '0e1791e9db3bd21a9122c416', plain: 'Hello node.js world!', - password: 'very bad password', aad: '63616c76696e', - ct: 'DDA53A4059AA17B88756984995F7BBA3C636CC44', - tag: 'D2A35E5C611E5E3D2258360241C5B045', tampered: false } -]; - -var ciphers = crypto.getCiphers(); - -for (var i in TEST_CASES) { - var test = TEST_CASES[i]; - - if (ciphers.indexOf(test.algo) == -1) { - console.log('skipping unsupported ' + test.algo + ' test'); - continue; - } - - (function() { - var encrypt = crypto.createCipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); - if (test.aad) - encrypt.setAAD(new Buffer(test.aad, 'hex')); - var hex = encrypt.update(test.plain, 'ascii', 'hex'); - hex += encrypt.final('hex'); - var auth_tag = encrypt.getAuthTag(); - // only test basic encryption run if output is marked as tampered. - if (!test.tampered) { - assert.equal(hex.toUpperCase(), test.ct); - assert.equal(auth_tag.toString('hex').toUpperCase(), test.tag); - } - })(); - - (function() { - var decrypt = crypto.createDecipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); - decrypt.setAuthTag(new Buffer(test.tag, 'hex')); - if (test.aad) - decrypt.setAAD(new Buffer(test.aad, 'hex')); - var msg = decrypt.update(test.ct, 'hex', 'ascii'); - if (!test.tampered) { - msg += decrypt.final('ascii'); - assert.equal(msg, test.plain); - } else { - // assert that final throws if input data could not be verified! - assert.throws(function() { decrypt.final('ascii'); }, / auth/); - } - })(); - - (function() { - if (!test.password) return; - var encrypt = crypto.createCipher(test.algo, test.password); - if (test.aad) - encrypt.setAAD(new Buffer(test.aad, 'hex')); - var hex = encrypt.update(test.plain, 'ascii', 'hex'); - hex += encrypt.final('hex'); - var auth_tag = encrypt.getAuthTag(); - // only test basic encryption run if output is marked as tampered. - if (!test.tampered) { - assert.equal(hex.toUpperCase(), test.ct); - assert.equal(auth_tag.toString('hex').toUpperCase(), test.tag); - } - })(); - - (function() { - if (!test.password) return; - var decrypt = crypto.createDecipher(test.algo, test.password); - decrypt.setAuthTag(new Buffer(test.tag, 'hex')); - if (test.aad) - decrypt.setAAD(new Buffer(test.aad, 'hex')); - var msg = decrypt.update(test.ct, 'hex', 'ascii'); - if (!test.tampered) { - msg += decrypt.final('ascii'); - assert.equal(msg, test.plain); - } else { - // assert that final throws if input data could not be verified! - assert.throws(function() { decrypt.final('ascii'); }, / auth/); - } - })(); - - // after normal operation, test some incorrect ways of calling the API: - // it's most certainly enough to run these tests with one algorithm only. - - if (i > 0) { - continue; - } - - (function() { - // non-authenticating mode: - var encrypt = crypto.createCipheriv('aes-128-cbc', - 'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC'); - encrypt.update('blah', 'ascii'); - encrypt.final(); - assert.throws(function() { encrypt.getAuthTag(); }, / state/); - assert.throws(function() { - encrypt.setAAD(new Buffer('123', 'ascii')); }, / state/); - })(); - - (function() { - // trying to get tag before inputting all data: - var encrypt = crypto.createCipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); - encrypt.update('blah', 'ascii'); - assert.throws(function() { encrypt.getAuthTag(); }, / state/); - })(); - - (function() { - // trying to set tag on encryption object: - var encrypt = crypto.createCipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); - assert.throws(function() { - encrypt.setAuthTag(new Buffer(test.tag, 'hex')); }, / state/); - })(); - - (function() { - // trying to read tag from decryption object: - var decrypt = crypto.createDecipheriv(test.algo, - new Buffer(test.key, 'hex'), new Buffer(test.iv, 'hex')); - assert.throws(function() { decrypt.getAuthTag(); }, / state/); - })(); -} diff --git a/test/simple/test-crypto-binary-default.js b/test/simple/test-crypto-binary-default.js deleted file mode 100644 index fe7da668e..000000000 --- a/test/simple/test-crypto-binary-default.js +++ /dev/null @@ -1,693 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This is the same as test/simple/test-crypto, but from before the shift -// to use buffers by default. - - -var common = require('../common'); -var assert = require('assert'); -var constants = require('constants'); - -try { - var crypto = require('crypto'); - var tls = require('tls'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'binary'; - -var fs = require('fs'); -var path = require('path'); - -// Test Certificates -var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); -var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); -var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); -var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); -var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', - 'ascii'); -var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', - 'ascii'); - -// TODO(indutny): Move to a separate test eventually -try { - var context = tls.createSecureContext({ - key: keyPem, - cert: certPem, - ca: caPem - }); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -// PFX tests -assert.doesNotThrow(function() { - tls.createSecureContext({pfx:certPfx, passphrase:'sample'}); -}); - -assert.throws(function() { - tls.createSecureContext({pfx:certPfx}); -}, 'mac verify failure'); - -assert.throws(function() { - tls.createSecureContext({pfx:certPfx, passphrase:'test'}); -}, 'mac verify failure'); - -assert.throws(function() { - tls.createSecureContext({pfx:'sample', passphrase:'test'}); -}, 'not enough data'); - -// Test HMAC -var h1 = crypto.createHmac('sha1', 'Node') - .update('some data') - .update('to hmac') - .digest('hex'); -assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); - -// Test HMAC-SHA-* (rfc 4231 Test Cases) -var rfc4231 = [ - { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: new Buffer('4869205468657265', 'hex'), // 'Hi There' - hmac: { - sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', - sha256: - 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + - '2e32cff7', - sha384: - 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + - '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', - sha512: - '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + - '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + - '2e696c203a126854' - } - }, - { - key: new Buffer('4a656665', 'hex'), // 'Jefe' - data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + - '96e673f', 'hex'), // 'what do ya want for nothing?' - hmac: { - sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', - sha256: - '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + - '64ec3843', - sha384: - 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + - '6322445e8e2240ca5e69e2c78b3239ecfab21649', - sha512: - '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + - 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + - '636e070a38bce737' - } - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + - 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), - hmac: { - sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', - sha256: - '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + - 'ced565fe', - sha384: - '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + - '5966144b2a5ab39dc13814b94e3ab6e101a34f27', - sha512: - 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + - 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + - '74278859e13292fb' - } - }, - { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + - 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', - 'hex'), - hmac: { - sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', - sha256: - '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + - '6729665b', - sha384: - '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + - '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', - sha512: - 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + - '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + - 'e2adebeb10a298dd' - } - }, - - { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), - // 'Test With Truncation' - data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), - hmac: { - sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', - sha256: 'a3b6167473100ee06e0c796c2955552b', - sha384: '3abf34c3503b2a23a46efc619baef897', - sha512: '415fad6271580a531d4179bc891d87a6' - }, - truncate: true - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaa', 'hex'), - // 'Test Using Larger Than Block-Size Key - Hash Key First' - data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + - 'c6f636b2d53697a65204b6579202d2048617368204b657920' + - '4669727374', 'hex'), - hmac: { - sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', - sha256: - '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + - '0ee37f54', - sha384: - '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + - '033ac4c60c2ef6ab4030fe8296248df163f44952', - sha512: - '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + - '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + - '8b915a985d786598' - } - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaa', 'hex'), - // 'This is a test using a larger than block-size key and a larger ' + - // 'than block-size data. The key needs to be hashed before being ' + - // 'used by the HMAC algorithm.' - data: new Buffer('5468697320697320612074657374207573696e672061206c6' + - '172676572207468616e20626c6f636b2d73697a65206b6579' + - '20616e642061206c6172676572207468616e20626c6f636b2' + - 'd73697a6520646174612e20546865206b6579206e65656473' + - '20746f20626520686173686564206265666f7265206265696' + - 'e6720757365642062792074686520484d414320616c676f72' + - '6974686d2e', 'hex'), - hmac: { - sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', - sha256: - '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + - '5c3a35e2', - sha384: - '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + - '461e99c5a678cc31e799176d3860e6110c46523e', - sha512: - 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + - '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + - '65c97440fa8c6a58' - } - } -]; - -for (var i = 0, l = rfc4231.length; i < l; i++) { - for (var hash in rfc4231[i]['hmac']) { - var result = crypto.createHmac(hash, rfc4231[i]['key']) - .update(rfc4231[i]['data']) - .digest('hex'); - if (rfc4231[i]['truncate']) { - result = result.substr(0, 32); // first 128 bits == 32 hex chars - } - assert.equal(rfc4231[i]['hmac'][hash], - result, - 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); - } -} - -// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) -var rfc2202_md5 = [ - { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: 'Hi There', - hmac: '9294727a3638bb1c13f48ef8158bfc9d' - }, - { - key: 'Jefe', - data: 'what do ya want for nothing?', - hmac: '750c783e6ab0b503eaa86e310a5db738' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + - 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), - hmac: '56be34521d144c88dbb8c733f0e8b3f6' - }, - { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + - 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + - 'cdcdcdcdcd', - 'hex'), - hmac: '697eaf0aca3a3aea3a75164746ffaa79' - }, - { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), - data: 'Test With Truncation', - hmac: '56461ef2342edc00f9bab995690efd4c' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: 'Test Using Larger Than Block-Size Key - Hash Key First', - hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: - 'Test Using Larger Than Block-Size Key and Larger Than One ' + - 'Block-Size Data', - hmac: '6f630fad67cda0ee1fb1f562db3aa53e' - } -]; -var rfc2202_sha1 = [ - { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: 'Hi There', - hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' - }, - { - key: 'Jefe', - data: 'what do ya want for nothing?', - hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + - 'ddddddddddddddddddddddddddddddddddddddddddddd' + - 'dddddddddd', - 'hex'), - hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' - }, - { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + - 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + - 'cdcdcdcdcd', - 'hex'), - hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' - }, - { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), - data: 'Test With Truncation', - hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: 'Test Using Larger Than Block-Size Key - Hash Key First', - hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: - 'Test Using Larger Than Block-Size Key and Larger Than One ' + - 'Block-Size Data', - hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' - } -]; - -for (var i = 0, l = rfc2202_md5.length; i < l; i++) { - assert.equal(rfc2202_md5[i]['hmac'], - crypto.createHmac('md5', rfc2202_md5[i]['key']) - .update(rfc2202_md5[i]['data']) - .digest('hex'), - 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); -} -for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { - assert.equal(rfc2202_sha1[i]['hmac'], - crypto.createHmac('sha1', rfc2202_sha1[i]['key']) - .update(rfc2202_sha1[i]['data']) - .digest('hex'), - 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); -} - -// Test hashing -var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); -var a1 = crypto.createHash('md5').update('Test123').digest('binary'); -var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); -var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary -var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); - -assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); -assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + - '\u00bd\u008c', 'Test MD5 as binary'); -assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', - 'Test SHA256 as base64'); - -assert.equal(a3, '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + - '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + - '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + - '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + - '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', - 'Test SHA512 as assumed binary'); - -assert.deepEqual(a4, - new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), - 'Test SHA1'); - -// Test multiple updates to same hash -var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); -var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); -assert.equal(h1, h2, 'multipled updates'); - -// Test hashing for binary files -var fn = path.join(common.fixturesDir, 'sample.png'); -var sha1Hash = crypto.createHash('sha1'); -var fileStream = fs.createReadStream(fn); -fileStream.on('data', function(data) { - sha1Hash.update(data); -}); -fileStream.on('close', function() { - assert.equal(sha1Hash.digest('hex'), - '22723e553129a336ad96e10f6aecdf0f45e4149e', - 'Test SHA1 of sample.png'); -}); - -// Issue #2227: unknown digest method should throw an error. -assert.throws(function() { - crypto.createHash('xyzzy'); -}); - -// Test signing and verifying -var s1 = crypto.createSign('RSA-SHA1') - .update('Test123') - .sign(keyPem, 'base64'); -var verified = crypto.createVerify('RSA-SHA1') - .update('Test') - .update('123') - .verify(certPem, s1, 'base64'); -assert.strictEqual(verified, true, 'sign and verify (base 64)'); - -var s2 = crypto.createSign('RSA-SHA256') - .update('Test123') - .sign(keyPem); // binary -var verified = crypto.createVerify('RSA-SHA256') - .update('Test') - .update('123') - .verify(certPem, s2); // binary -assert.strictEqual(verified, true, 'sign and verify (binary)'); - -var s3 = crypto.createSign('RSA-SHA1') - .update('Test123') - .sign(keyPem, 'buffer'); -var verified = crypto.createVerify('RSA-SHA1') - .update('Test') - .update('123') - .verify(certPem, s3); -assert.strictEqual(verified, true, 'sign and verify (buffer)'); - - -function testCipher1(key) { - // Test encryption and decryption - var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - var cipher = crypto.createCipher('aes192', key); - - // encrypt plaintext which is in utf8 format - // to a ciphertext which will be in hex - var ciph = cipher.update(plaintext, 'utf8', 'hex'); - // Only use binary or hex, not base64. - ciph += cipher.final('hex'); - - var decipher = crypto.createDecipher('aes192', key); - var txt = decipher.update(ciph, 'hex', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption'); -} - - -function testCipher2(key) { - // encryption and decryption with Base64 - // reported in https://github.com/joyent/node/issues/738 - var plaintext = - '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + - 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + - 'jAfaFg**'; - var cipher = crypto.createCipher('aes256', key); - - // encrypt plaintext which is in utf8 format - // to a ciphertext which will be in Base64 - var ciph = cipher.update(plaintext, 'utf8', 'base64'); - ciph += cipher.final('base64'); - - var decipher = crypto.createDecipher('aes256', key); - var txt = decipher.update(ciph, 'base64', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with Base64'); -} - - -function testCipher3(key, iv) { - // Test encyrption and decryption with explicit key and iv - var plaintext = - '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + - 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + - 'jAfaFg**'; - var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); - var ciph = cipher.update(plaintext, 'utf8', 'hex'); - ciph += cipher.final('hex'); - - var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); - var txt = decipher.update(ciph, 'hex', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); -} - - -function testCipher4(key, iv) { - // Test encyrption and decryption with explicit key and iv - var plaintext = - '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + - 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + - 'jAfaFg**'; - var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); - var ciph = cipher.update(plaintext, 'utf8', 'buffer'); - ciph = Buffer.concat([ciph, cipher.final('buffer')]); - - var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); - var txt = decipher.update(ciph, 'buffer', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); -} - - -testCipher1('MySecretKey123'); -testCipher1(new Buffer('MySecretKey123')); - -testCipher2('0123456789abcdef'); -testCipher2(new Buffer('0123456789abcdef')); - -testCipher3('0123456789abcd0123456789', '12345678'); -testCipher3('0123456789abcd0123456789', new Buffer('12345678')); -testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); -testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); - -testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); - - -// update() should only take buffers / strings -assert.throws(function() { - crypto.createHash('sha1').update({foo: 'bar'}); -}, /buffer/); - - -// Test Diffie-Hellman with two parties sharing a secret, -// using various encodings as we go along -var dh1 = crypto.createDiffieHellman(256); -var p1 = dh1.getPrime('buffer'); -var dh2 = crypto.createDiffieHellman(p1, 'base64'); -var key1 = dh1.generateKeys(); -var key2 = dh2.generateKeys('hex'); -var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); -var secret2 = dh2.computeSecret(key1, 'binary', 'buffer'); - -assert.equal(secret1, secret2.toString('base64')); - -// Create "another dh1" using generated keys from dh1, -// and compute secret again -var dh3 = crypto.createDiffieHellman(p1, 'buffer'); -var privkey1 = dh1.getPrivateKey(); -dh3.setPublicKey(key1); -dh3.setPrivateKey(privkey1); - -assert.equal(dh1.getPrime(), dh3.getPrime()); -assert.equal(dh1.getGenerator(), dh3.getGenerator()); -assert.equal(dh1.getPublicKey(), dh3.getPublicKey()); -assert.equal(dh1.getPrivateKey(), dh3.getPrivateKey()); - -var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); - -assert.equal(secret1, secret3); - -// https://github.com/joyent/node/issues/2338 -var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + - '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + - '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + - 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; -var d = crypto.createDiffieHellman(p, 'hex'); -assert.equal(d.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - -// Test RSA key signing/verification -var rsaSign = crypto.createSign('RSA-SHA1'); -var rsaVerify = crypto.createVerify('RSA-SHA1'); -assert.ok(rsaSign); -assert.ok(rsaVerify); - -rsaSign.update(rsaPubPem); -var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); -assert.equal(rsaSignature, - '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + - '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + - 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + - '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + - '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); - -rsaVerify.update(rsaPubPem); -assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); - - -// -// Test RSA signing and verification -// -(function() { - var privateKey = fs.readFileSync( - common.fixturesDir + '/test_rsa_privkey_2.pem'); - - var publicKey = fs.readFileSync( - common.fixturesDir + '/test_rsa_pubkey_2.pem'); - - var input = 'I AM THE WALRUS'; - - var signature = - '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + - '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + - '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + - '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + - '0ddfb299bedeb1ad'; - - var sign = crypto.createSign('RSA-SHA256'); - sign.update(input); - - var output = sign.sign(privateKey, 'hex'); - assert.equal(output, signature); - - var verify = crypto.createVerify('RSA-SHA256'); - verify.update(input); - - assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); - - -// -// Test DSA signing and verification -// -(function() { - var privateKey = fs.readFileSync( - common.fixturesDir + '/test_dsa_privkey.pem'); - - var publicKey = fs.readFileSync( - common.fixturesDir + '/test_dsa_pubkey.pem'); - - var input = 'I AM THE WALRUS'; - - // DSA signatures vary across runs so there is no static string to verify - // against - var sign = crypto.createSign('DSS1'); - sign.update(input); - var signature = sign.sign(privateKey, 'hex'); - - var verify = crypto.createVerify('DSS1'); - verify.update(input); - - assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); - - -// -// Test PBKDF2 with RFC 6070 test vectors (except #4) -// -function testPBKDF2(password, salt, iterations, keylen, expected) { - var actual = crypto.pbkdf2Sync(password, salt, iterations, keylen); - assert.equal(actual, expected); - - crypto.pbkdf2(password, salt, iterations, keylen, function(err, actual) { - assert.equal(actual, expected); - }); -} - - -testPBKDF2('password', 'salt', 1, 20, - '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + - '\xaf\x60\x12\x06\x2f\xe0\x37\xa6'); - -testPBKDF2('password', 'salt', 2, 20, - '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + - '\xce\x1d\x41\xf0\xd8\xde\x89\x57'); - -testPBKDF2('password', 'salt', 4096, 20, - '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + - '\xf7\x21\xd0\x65\xa4\x29\xc1'); - -testPBKDF2('passwordPASSWORDpassword', - 'saltSALTsaltSALTsaltSALTsaltSALTsalt', - 4096, - 25, - '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + - '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38'); - -testPBKDF2('pass\0word', 'sa\0lt', 4096, 16, - '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + - '\x25\xe0\xc3'); diff --git a/test/simple/test-crypto-certificate.js b/test/simple/test-crypto-certificate.js deleted file mode 100644 index 60fedee74..000000000 --- a/test/simple/test-crypto-certificate.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var crypto = require('crypto'); - -crypto.DEFAULT_ENCODING = 'buffer'; - -var fs = require('fs'); -var path = require('path'); - -// Test Certificates -var spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); -var spkacFail = fs.readFileSync(common.fixturesDir + '/spkac.fail'); -var spkacPem = fs.readFileSync(common.fixturesDir + '/spkac.pem'); - -var certificate = new crypto.Certificate(); - -assert.equal(certificate.verifySpkac(spkacValid), true); -assert.equal(certificate.verifySpkac(spkacFail), false); - -assert.equal(stripLineEndings(certificate.exportPublicKey(spkacValid) - .toString('utf8')), - stripLineEndings(spkacPem.toString('utf8'))); -assert.equal(certificate.exportPublicKey(spkacFail), ''); - -assert.equal(certificate.exportChallenge(spkacValid) - .toString('utf8'), - 'fb9ab814-6677-42a4-a60c-f905d1a6924d'); -assert.equal(certificate.exportChallenge(spkacFail), ''); - -function stripLineEndings(obj) { - return obj.replace(/\n/g, ''); -} diff --git a/test/simple/test-crypto-dh-odd-key.js b/test/simple/test-crypto-dh-odd-key.js deleted file mode 100644 index a3d99e9b5..000000000 --- a/test/simple/test-crypto-dh-odd-key.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var crypto = require('crypto'); -var odd = new Buffer(39); -odd.fill('A'); - -var c = crypto.createDiffieHellman(32); -c.setPrivateKey(odd); -c.generateKeys(); diff --git a/test/simple/test-crypto-domain.js b/test/simple/test-crypto-domain.js deleted file mode 100644 index 6284afc07..000000000 --- a/test/simple/test-crypto-domain.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Skipping test, compiled without crypto support.'); - return; -} - -function test(fn) { - var ex = new Error('BAM'); - var d = domain.create(); - d.on('error', common.mustCall(function(err) { - assert.equal(err, ex); - })); - var cb = common.mustCall(function() { - throw ex; - }); - d.run(cb); -} - -test(function(cb) { - crypto.pbkdf2('password', 'salt', 1, 8, cb); -}); - -test(function(cb) { - crypto.randomBytes(32, cb); -}); diff --git a/test/simple/test-crypto-domains.js b/test/simple/test-crypto-domains.js deleted file mode 100644 index 1393f6da1..000000000 --- a/test/simple/test-crypto-domains.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. - -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: - -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var crypto = require('crypto'); -var domain = require('domain'); -var assert = require('assert'); -var d = domain.create(); -var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes'] -var errors = 0; - -process.on('exit', function() { - assert.equal(errors, 3); -}); - -d.on('error', function (e) { - assert.equal(e.message, expect.shift()); - errors += 1; -}); - -d.run(function () { - one(); - - function one() { - crypto.pbkdf2('a', 'b', 1, 8, function () { - two(); - throw new Error('pbkdf2'); - }); - } - - function two() { - crypto.randomBytes(4, function () { - three(); - throw new Error('randomBytes'); - }); - } - - function three() { - crypto.pseudoRandomBytes(4, function () { - throw new Error('pseudoRandomBytes'); - }); - } -}); diff --git a/test/simple/test-crypto-ecb.js b/test/simple/test-crypto-ecb.js deleted file mode 100644 index e5b893cfc..000000000 --- a/test/simple/test-crypto-ecb.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - -// Testing whether EVP_CipherInit_ex is functioning correctly. -// Reference: bug#1997 - -(function() { - var encrypt = crypto.createCipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', ''); - var hex = encrypt.update('Hello World!', 'ascii', 'hex'); - hex += encrypt.final('hex'); - assert.equal(hex.toUpperCase(), '6D385F424AAB0CFBF0BB86E07FFB7D71'); -}()); - -(function() { - var decrypt = crypto.createDecipheriv('BF-ECB', 'SomeRandomBlahz0c5GZVnR', - ''); - var msg = decrypt.update('6D385F424AAB0CFBF0BB86E07FFB7D71', 'hex', 'ascii'); - msg += decrypt.final('ascii'); - assert.equal(msg, 'Hello World!'); -}()); diff --git a/test/simple/test-crypto-from-binary.js b/test/simple/test-crypto-from-binary.js deleted file mode 100644 index 203361700..000000000 --- a/test/simple/test-crypto-from-binary.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This is the same as test/simple/test-crypto, but from before the shift -// to use buffers by default. - - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -var EXTERN_APEX = 0xFBEE9; - -// manually controlled string for checking binary output -var ucs2_control = 'a\u0000'; - -// grow the strings to proper length -while (ucs2_control.length <= EXTERN_APEX) { - ucs2_control += ucs2_control; -} - - -// check resultant buffer and output string -var b = new Buffer(ucs2_control + ucs2_control, 'ucs2'); - -// -// Test updating from birant data -// -(function() { - var datum1 = b.slice(700000); - var hash1_converted = crypto.createHash('sha1') - .update(datum1.toString('base64'), 'base64') - .digest('hex'); - var hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); - assert.equal(hash1_direct, hash1_converted, 'should hash the same.'); - - var datum2 = b; - var hash2_converted = crypto.createHash('sha1') - .update(datum2.toString('base64'), 'base64') - .digest('hex'); - var hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); - assert.equal(hash2_direct, hash2_converted, 'should hash the same.'); -})(); diff --git a/test/simple/test-crypto-hash-stream-pipe.js b/test/simple/test-crypto-hash-stream-pipe.js deleted file mode 100644 index 1394903fa..000000000 --- a/test/simple/test-crypto-hash-stream-pipe.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var crypto = require('crypto'); -var stream = require('stream') -var s = new stream.PassThrough(); -var h = crypto.createHash('sha1'); -var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; -var gotData = false; - -process.on('exit', function() { - assert(gotData); - console.log('ok'); -}); - -s.pipe(h).on('data', function(c) { - assert.equal(c, expect); - gotData = true; -}).setEncoding('hex'); - -s.end('aoeu'); diff --git a/test/simple/test-crypto-padding-aes256.js b/test/simple/test-crypto-padding-aes256.js deleted file mode 100644 index dd293feb1..000000000 --- a/test/simple/test-crypto-padding-aes256.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OpenSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - -function aes256(decipherFinal) { - var iv = new Buffer('00000000000000000000000000000000', 'hex'); - var key = new Buffer('0123456789abcdef0123456789abcdef' + - '0123456789abcdef0123456789abcdef', 'hex'); - - function encrypt(val, pad) { - var c = crypto.createCipheriv('aes256', key, iv); - c.setAutoPadding(pad); - return c.update(val, 'utf8', 'binary') + c.final('binary'); - } - - function decrypt(val, pad) { - var c = crypto.createDecipheriv('aes256', key, iv); - c.setAutoPadding(pad); - return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); - } - - // echo 0123456789abcdef0123456789abcdef \ - // | openssl enc -e -aes256 -nopad -K -iv \ - // | openssl enc -d -aes256 -nopad -K -iv - var plaintext = '0123456789abcdef0123456789abcdef'; // multiple of block size - var encrypted = encrypt(plaintext, false); - var decrypted = decrypt(encrypted, false); - assert.equal(decrypted, plaintext); - - // echo 0123456789abcdef0123456789abcde \ - // | openssl enc -e -aes256 -K -iv \ - // | openssl enc -d -aes256 -K -iv - plaintext = '0123456789abcdef0123456789abcde'; // not a multiple - encrypted = encrypt(plaintext, true); - decrypted = decrypt(encrypted, true); - assert.equal(decrypted, plaintext); -} - -aes256('final'); -aes256('finaltol'); diff --git a/test/simple/test-crypto-padding.js b/test/simple/test-crypto-padding.js deleted file mode 100644 index 22edbf481..000000000 --- a/test/simple/test-crypto-padding.js +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - - -/* - * Input data - */ - -var ODD_LENGTH_PLAIN = 'Hello node world!', - EVEN_LENGTH_PLAIN = 'Hello node world!AbC09876dDeFgHi'; - -var KEY_PLAIN = 'S3c.r.e.t.K.e.Y!', - IV_PLAIN = 'blahFizz2011Buzz'; - -var CIPHER_NAME = 'aes-128-cbc'; - - -/* - * Expected result data - */ - -// echo -n 'Hello node world!' | \ -// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ -// -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 -var ODD_LENGTH_ENCRYPTED = - '7f57859550d4d2fdb9806da2a750461a9fe77253cd1cbd4b07beee4e070d561f'; - -// echo -n 'Hello node world!AbC09876dDeFgHi' | \ -// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ -// -iv 626c616846697a7a3230313142757a7a | xxd -p -c256 -var EVEN_LENGTH_ENCRYPTED = - '7f57859550d4d2fdb9806da2a750461ab46e71b3d78ebe2d9684dfc87f7575b988' + - '6119866912cb8c7bcaf76c5ebc2378'; - -// echo -n 'Hello node world!AbC09876dDeFgHi' | \ -// openssl enc -aes-128-cbc -e -K 5333632e722e652e742e4b2e652e5921 \ -// -iv 626c616846697a7a3230313142757a7a -nopad | xxd -p -c256 -var EVEN_LENGTH_ENCRYPTED_NOPAD = - '7f57859550d4d2fdb9806da2a750461ab46e' + - '71b3d78ebe2d9684dfc87f7575b9'; - - -/* - * Helper wrappers - */ - -function enc(plain, pad) { - var encrypt = crypto.createCipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); - encrypt.setAutoPadding(pad); - var hex = encrypt.update(plain, 'ascii', 'hex'); - hex += encrypt.final('hex'); - return hex; -} - -function dec(encd, pad) { - var decrypt = crypto.createDecipheriv(CIPHER_NAME, KEY_PLAIN, IV_PLAIN); - decrypt.setAutoPadding(pad); - var plain = decrypt.update(encd, 'hex'); - plain += decrypt.final('binary'); - return plain; -} - - -/* - * Test encryption - */ - -assert.equal(enc(ODD_LENGTH_PLAIN, true), ODD_LENGTH_ENCRYPTED); -assert.equal(enc(EVEN_LENGTH_PLAIN, true), EVEN_LENGTH_ENCRYPTED); - -assert.throws(function() { - // input must have block length % - enc(ODD_LENGTH_PLAIN, false); -}); - -assert.doesNotThrow(function() { - assert.equal(enc(EVEN_LENGTH_PLAIN, false), EVEN_LENGTH_ENCRYPTED_NOPAD); -}); - - -/* - * Test decryption - */ - -assert.equal(dec(ODD_LENGTH_ENCRYPTED, true), ODD_LENGTH_PLAIN); -assert.equal(dec(EVEN_LENGTH_ENCRYPTED, true), EVEN_LENGTH_PLAIN); - -assert.doesNotThrow(function() { - // returns including original padding - assert.equal(dec(ODD_LENGTH_ENCRYPTED, false).length, 32); - assert.equal(dec(EVEN_LENGTH_ENCRYPTED, false).length, 48); -}); - -assert.throws(function() { - // must have at least 1 byte of padding (PKCS): - assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, true), EVEN_LENGTH_PLAIN); -}); - -assert.doesNotThrow(function() { - // no-pad encrypted string should return the same: - assert.equal(dec(EVEN_LENGTH_ENCRYPTED_NOPAD, false), EVEN_LENGTH_PLAIN); -}); diff --git a/test/simple/test-crypto-random.js b/test/simple/test-crypto-random.js deleted file mode 100644 index 24a76f4f1..000000000 --- a/test/simple/test-crypto-random.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - -// bump, we register a lot of exit listeners -process.setMaxListeners(256); - -[crypto.randomBytes, - crypto.pseudoRandomBytes -].forEach(function(f) { - [-1, - undefined, - null, - false, - true, - {}, - [] - ].forEach(function(value) { - assert.throws(function() { f(value); }); - assert.throws(function() { f(value, function() {}); }); - }); - - [0, 1, 2, 4, 16, 256, 1024].forEach(function(len) { - f(len, checkCall(function(ex, buf) { - assert.equal(null, ex); - assert.equal(len, buf.length); - assert.ok(Buffer.isBuffer(buf)); - })); - }); -}); - -// assert that the callback is indeed called -function checkCall(cb, desc) { - var called_ = false; - - process.on('exit', function() { - assert.equal(true, called_, desc || ('callback not called: ' + cb)); - }); - - return function() { - return called_ = true, cb.apply(cb, Array.prototype.slice.call(arguments)); - }; -} - -// #5126, "FATAL ERROR: v8::Object::SetIndexedPropertiesToExternalArrayData() -// length exceeds max acceptable value" -assert.throws(function() { - crypto.randomBytes(0x3fffffff + 1); -}, TypeError); diff --git a/test/simple/test-crypto-stream.js b/test/simple/test-crypto-stream.js deleted file mode 100644 index ff58e8040..000000000 --- a/test/simple/test-crypto-stream.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var stream = require('stream'); -var util = require('util'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -// Small stream to buffer converter -function Stream2buffer(callback) { - stream.Writable.call(this); - - this._buffers = []; - this.once('finish', function () { - callback(null, Buffer.concat(this._buffers)); - }); -} -util.inherits(Stream2buffer, stream.Writable); - -Stream2buffer.prototype._write = function (data, encodeing, done) { - this._buffers.push(data); - return done(null); -}; - -// Create an md5 hash of "Hallo world" -var hasher1 = crypto.createHash('md5'); - hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { - assert.equal(err, null); - assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); - }))); - hasher1.end('Hallo world'); - -// Simpler check for unpipe, setEncoding, pause and resume -crypto.createHash('md5').unpipe({}); -crypto.createHash('md5').setEncoding('utf8'); -crypto.createHash('md5').pause(); -crypto.createHash('md5').resume(); - -// Decipher._flush() should emit an error event, not an exception. -var key = new Buffer('48fb56eb10ffeb13fc0ef551bbca3b1b', 'hex'), - badkey = new Buffer('12341234123412341234123412341234', 'hex'), - iv = new Buffer('6d358219d1f488f5f4eb12820a66d146', 'hex'), - cipher = crypto.createCipheriv('aes-128-cbc', key, iv), - decipher = crypto.createDecipheriv('aes-128-cbc', badkey, iv); - -cipher.pipe(decipher) - .on('error', common.mustCall(function end(err) { - assert(/Unsupported/.test(err)); - })); - -cipher.end('Papaya!'); // Should not cause an unhandled exception. diff --git a/test/simple/test-crypto-verify-failure.js b/test/simple/test-crypto-verify-failure.js deleted file mode 100644 index 09c43ddc0..000000000 --- a/test/simple/test-crypto-verify-failure.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); - var tls = require('tls'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - -var fs = require('fs'); - -var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var canSend = true; - -var server = tls.Server(options, function(socket) { - setImmediate(function() { - console.log('sending'); - verify(); - setImmediate(function() { - socket.destroy(); - }); - }); -}); - -var client; - -function verify() { - console.log('verify'); - var verified = crypto.createVerify('RSA-SHA1') - .update('Test') - .verify(certPem, 'asdfasdfas', 'base64'); -} - -server.listen(common.PORT, function() { - client = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - verify(); - }).on('data', function(data) { - console.log(data); - }).on('error', function(err) { - throw err; - }).on('close', function() { - server.close(); - }).resume(); -}); - -server.unref(); diff --git a/test/simple/test-crypto.js b/test/simple/test-crypto.js deleted file mode 100644 index d3f1ade32..000000000 --- a/test/simple/test-crypto.js +++ /dev/null @@ -1,1220 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -crypto.DEFAULT_ENCODING = 'buffer'; - -var fs = require('fs'); -var path = require('path'); -var constants = require('constants'); - -// Test Certificates -var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii'); -var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); -var certPfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); -var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); -var rsaPubPem = fs.readFileSync(common.fixturesDir + '/test_rsa_pubkey.pem', - 'ascii'); -var rsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_rsa_privkey.pem', - 'ascii'); -var rsaKeyPemEncrypted = fs.readFileSync( - common.fixturesDir + '/test_rsa_privkey_encrypted.pem', 'ascii'); -var dsaPubPem = fs.readFileSync(common.fixturesDir + '/test_dsa_pubkey.pem', - 'ascii'); -var dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem', - 'ascii'); -var dsaKeyPemEncrypted = fs.readFileSync( - common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); - - -// TODO(indunty): move to a separate test eventually -try { - var tls = require('tls'); - var context = tls.createSecureContext({ - key: keyPem, - cert: certPem, - ca: caPem - }); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -// 'this' safety -// https://github.com/joyent/node/issues/6690 -assert.throws(function() { - var options = {key: keyPem, cert: certPem, ca: caPem}; - var credentials = crypto.createCredentials(options); - var context = credentials.context; - var notcontext = { setOptions: context.setOptions, setKey: context.setKey }; - crypto.createCredentials({ secureOptions: 1 }, notcontext); -}, TypeError); - -// PFX tests -assert.doesNotThrow(function() { - tls.createSecureContext({pfx:certPfx, passphrase:'sample'}); -}); - -assert.throws(function() { - tls.createSecureContext({pfx:certPfx}); -}, 'mac verify failure'); - -assert.throws(function() { - tls.createSecureContext({pfx:certPfx, passphrase:'test'}); -}, 'mac verify failure'); - -assert.throws(function() { - tls.createSecureContext({pfx:'sample', passphrase:'test'}); -}, 'not enough data'); - -// Test HMAC -var h1 = crypto.createHmac('sha1', 'Node') - .update('some data') - .update('to hmac') - .digest('hex'); -assert.equal(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); - -// Test HMAC (Wikipedia Test Cases) -var wikipedia = [ - { - key: 'key', data: 'The quick brown fox jumps over the lazy dog', - hmac: { // HMACs lifted from Wikipedia. - md5: '80070713463e7749b90c2dc24911e275', - sha1: 'de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9', - sha256: - 'f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc' + - '2d1a3cd8' - } - }, - { - key: 'key', data: '', - hmac: { // Intermediate test to help debugging. - md5: '63530468a04e386459855da0063b6596', - sha1: 'f42bb0eeb018ebbd4597ae7213711ec60760843f', - sha256: - '5d5d139563c95b5967b9bd9a8c9b233a9dedb45072794cd232dc1b74' + - '832607d0' - } - }, - { - key: '', data: 'The quick brown fox jumps over the lazy dog', - hmac: { // Intermediate test to help debugging. - md5: 'ad262969c53bc16032f160081c4a07a0', - sha1: '2ba7f707ad5f187c412de3106583c3111d668de8', - sha256: - 'fb011e6154a19b9a4c767373c305275a5a69e8b68b0b4c9200c383dc' + - 'ed19a416' - } - }, - { - key: '', data: '', - hmac: { // HMACs lifted from Wikipedia. - md5: '74e6f7298a9c2d168935f58c001bad88', - sha1: 'fbdb1d1b18aa6c08324b7d64b71fb76370690e1d', - sha256: - 'b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c71214' + - '4292c5ad' - } - }, -] - -for (var i = 0, l = wikipedia.length; i < l; i++) { - for (var hash in wikipedia[i]['hmac']) { - var result = crypto.createHmac(hash, wikipedia[i]['key']) - .update(wikipedia[i]['data']) - .digest('hex'); - assert.equal(wikipedia[i]['hmac'][hash], - result, - 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' wikipedia'); - } -} - - -// Test HMAC-SHA-* (rfc 4231 Test Cases) -var rfc4231 = [ - { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: new Buffer('4869205468657265', 'hex'), // 'Hi There' - hmac: { - sha224: '896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22', - sha256: - 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c' + - '2e32cff7', - sha384: - 'afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c' + - '7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6', - sha512: - '87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b305' + - '45e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f170' + - '2e696c203a126854' - } - }, - { - key: new Buffer('4a656665', 'hex'), // 'Jefe' - data: new Buffer('7768617420646f2079612077616e7420666f72206e6f74686' + - '96e673f', 'hex'), // 'what do ya want for nothing?' - hmac: { - sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44', - sha256: - '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b9' + - '64ec3843', - sha384: - 'af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec373' + - '6322445e8e2240ca5e69e2c78b3239ecfab21649', - sha512: - '164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7' + - 'ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b' + - '636e070a38bce737' - } - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + - 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), - hmac: { - sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea', - sha256: - '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514' + - 'ced565fe', - sha384: - '88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e5' + - '5966144b2a5ab39dc13814b94e3ab6e101a34f27', - sha512: - 'fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33' + - 'b2279d39bf3e848279a722c806b485a47e67c807b946a337bee89426' + - '74278859e13292fb' - } - }, - { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + - 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', - 'hex'), - hmac: { - sha224: '6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a', - sha256: - '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff4' + - '6729665b', - sha384: - '3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e' + - '1f573b4e6801dd23c4a7d679ccf8a386c674cffb', - sha512: - 'b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050' + - '361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2d' + - 'e2adebeb10a298dd' - } - }, - - { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), - // 'Test With Truncation' - data: new Buffer('546573742057697468205472756e636174696f6e', 'hex'), - hmac: { - sha224: '0e2aea68a90c8d37c988bcdb9fca6fa8', - sha256: 'a3b6167473100ee06e0c796c2955552b', - sha384: '3abf34c3503b2a23a46efc619baef897', - sha512: '415fad6271580a531d4179bc891d87a6' - }, - truncate: true - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaa', 'hex'), - // 'Test Using Larger Than Block-Size Key - Hash Key First' - data: new Buffer('54657374205573696e67204c6172676572205468616e20426' + - 'c6f636b2d53697a65204b6579202d2048617368204b657920' + - '4669727374', 'hex'), - hmac: { - sha224: '95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e', - sha256: - '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f' + - '0ee37f54', - sha384: - '4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05' + - '033ac4c60c2ef6ab4030fe8296248df163f44952', - sha512: - '80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b0137' + - '83f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec' + - '8b915a985d786598' - } - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaa', 'hex'), - // 'This is a test using a larger than block-size key and a larger ' + - // 'than block-size data. The key needs to be hashed before being ' + - // 'used by the HMAC algorithm.' - data: new Buffer('5468697320697320612074657374207573696e672061206c6' + - '172676572207468616e20626c6f636b2d73697a65206b6579' + - '20616e642061206c6172676572207468616e20626c6f636b2' + - 'd73697a6520646174612e20546865206b6579206e65656473' + - '20746f20626520686173686564206265666f7265206265696' + - 'e6720757365642062792074686520484d414320616c676f72' + - '6974686d2e', 'hex'), - hmac: { - sha224: '3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1', - sha256: - '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f5153' + - '5c3a35e2', - sha384: - '6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82' + - '461e99c5a678cc31e799176d3860e6110c46523e', - sha512: - 'e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d' + - '20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de04460' + - '65c97440fa8c6a58' - } - } -]; - -for (var i = 0, l = rfc4231.length; i < l; i++) { - for (var hash in rfc4231[i]['hmac']) { - var str = crypto.createHmac(hash, rfc4231[i].key); - str.end(rfc4231[i].data); - var strRes = str.read().toString('hex'); - var result = crypto.createHmac(hash, rfc4231[i]['key']) - .update(rfc4231[i]['data']) - .digest('hex'); - if (rfc4231[i]['truncate']) { - result = result.substr(0, 32); // first 128 bits == 32 hex chars - strRes = strRes.substr(0, 32); - } - assert.equal(rfc4231[i]['hmac'][hash], - result, - 'Test HMAC-' + hash + ': Test case ' + (i + 1) + ' rfc 4231'); - assert.equal(strRes, result, 'Should get same result from stream'); - } -} - -// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) -var rfc2202_md5 = [ - { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: 'Hi There', - hmac: '9294727a3638bb1c13f48ef8158bfc9d' - }, - { - key: 'Jefe', - data: 'what do ya want for nothing?', - hmac: '750c783e6ab0b503eaa86e310a5db738' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddddddd' + - 'ddddddddddddddddddddddddddddddddddddddddddddddddddd', - 'hex'), - hmac: '56be34521d144c88dbb8c733f0e8b3f6' - }, - { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + - 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + - 'cdcdcdcdcd', - 'hex'), - hmac: '697eaf0aca3a3aea3a75164746ffaa79' - }, - { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), - data: 'Test With Truncation', - hmac: '56461ef2342edc00f9bab995690efd4c' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: 'Test Using Larger Than Block-Size Key - Hash Key First', - hmac: '6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: - 'Test Using Larger Than Block-Size Key and Larger Than One ' + - 'Block-Size Data', - hmac: '6f630fad67cda0ee1fb1f562db3aa53e' - } -]; -var rfc2202_sha1 = [ - { - key: new Buffer('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), - data: 'Hi There', - hmac: 'b617318655057264e28bc0b6fb378c8ef146be00' - }, - { - key: 'Jefe', - data: 'what do ya want for nothing?', - hmac: 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), - data: new Buffer('ddddddddddddddddddddddddddddddddddddddddddddd' + - 'ddddddddddddddddddddddddddddddddddddddddddddd' + - 'dddddddddd', - 'hex'), - hmac: '125d7342b9ac11cd91a39af48aa17b4f63f175d3' - }, - { - key: new Buffer('0102030405060708090a0b0c0d0e0f10111213141516171819', - 'hex'), - data: new Buffer('cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdc' + - 'dcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd' + - 'cdcdcdcdcd', - 'hex'), - hmac: '4c9007f4026250c6bc8414f9bf50c86c2d7235da' - }, - { - key: new Buffer('0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', 'hex'), - data: 'Test With Truncation', - hmac: '4c1a03424b55e07fe7f27be1d58bb9324a9a5a04' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: 'Test Using Larger Than Block-Size Key - Hash Key First', - hmac: 'aa4ae5e15272d00e95705637ce8a3b55ed402112' - }, - { - key: new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + - 'aaaaaaaaaaaaaaaaaaaaaa', - 'hex'), - data: - 'Test Using Larger Than Block-Size Key and Larger Than One ' + - 'Block-Size Data', - hmac: 'e8e99d0f45237d786d6bbaa7965c7808bbff1a91' - } -]; - -for (var i = 0, l = rfc2202_md5.length; i < l; i++) { - assert.equal(rfc2202_md5[i]['hmac'], - crypto.createHmac('md5', rfc2202_md5[i]['key']) - .update(rfc2202_md5[i]['data']) - .digest('hex'), - 'Test HMAC-MD5 : Test case ' + (i + 1) + ' rfc 2202'); -} -for (var i = 0, l = rfc2202_sha1.length; i < l; i++) { - assert.equal(rfc2202_sha1[i]['hmac'], - crypto.createHmac('sha1', rfc2202_sha1[i]['key']) - .update(rfc2202_sha1[i]['data']) - .digest('hex'), - 'Test HMAC-SHA1 : Test case ' + (i + 1) + ' rfc 2202'); -} - -// Test hashing -var a0 = crypto.createHash('sha1').update('Test123').digest('hex'); -var a1 = crypto.createHash('md5').update('Test123').digest('binary'); -var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); -var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary -var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); - -// stream interface -var a5 = crypto.createHash('sha512'); -a5.end('Test123'); -a5 = a5.read(); - -var a6 = crypto.createHash('sha512'); -a6.write('Te'); -a6.write('st'); -a6.write('123'); -a6.end(); -a6 = a6.read(); - -var a7 = crypto.createHash('sha512'); -a7.end(); -a7 = a7.read(); - -var a8 = crypto.createHash('sha512'); -a8.write(''); -a8.end(); -a8 = a8.read(); - -assert.equal(a0, '8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'Test SHA1'); -assert.equal(a1, 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca' + - '\u00bd\u008c', 'Test MD5 as binary'); -assert.equal(a2, '2bX1jws4GYKTlxhloUB09Z66PoJZW+y+hq5R8dnx9l4=', - 'Test SHA256 as base64'); -assert.deepEqual( - a3, - new Buffer( - '\u00c1(4\u00f1\u0003\u001fd\u0097!O\'\u00d4C/&Qz\u00d4' + - '\u0094\u0015l\u00b8\u008dQ+\u00db\u001d\u00c4\u00b5}\u00b2' + - '\u00d6\u0092\u00a3\u00df\u00a2i\u00a1\u009b\n\n*\u000f' + - '\u00d7\u00d6\u00a2\u00a8\u0085\u00e3<\u0083\u009c\u0093' + - '\u00c2\u0006\u00da0\u00a1\u00879(G\u00ed\'', - 'binary'), - 'Test SHA512 as assumed buffer'); -assert.deepEqual(a4, - new Buffer('8308651804facb7b9af8ffc53a33a22d6a1c8ac2', 'hex'), - 'Test SHA1'); - -// stream interface should produce the same result. -assert.deepEqual(a5, a3, 'stream interface is consistent'); -assert.deepEqual(a6, a3, 'stream interface is consistent'); -assert.notEqual(a7, undefined, 'no data should return data'); -assert.notEqual(a8, undefined, 'empty string should generate data'); - -// Test multiple updates to same hash -var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); -var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); -assert.equal(h1, h2, 'multipled updates'); - -// Test hashing for binary files -var fn = path.join(common.fixturesDir, 'sample.png'); -var sha1Hash = crypto.createHash('sha1'); -var fileStream = fs.createReadStream(fn); -fileStream.on('data', function(data) { - sha1Hash.update(data); -}); -fileStream.on('close', function() { - assert.equal(sha1Hash.digest('hex'), - '22723e553129a336ad96e10f6aecdf0f45e4149e', - 'Test SHA1 of sample.png'); -}); - -// Issue #2227: unknown digest method should throw an error. -assert.throws(function() { - crypto.createHash('xyzzy'); -}); - -// Test signing and verifying -var s1 = crypto.createSign('RSA-SHA1') - .update('Test123') - .sign(keyPem, 'base64'); -var s1stream = crypto.createSign('RSA-SHA1'); -s1stream.end('Test123'); -s1stream = s1stream.sign(keyPem, 'base64'); -assert.equal(s1, s1stream, 'Stream produces same output'); - -var verified = crypto.createVerify('RSA-SHA1') - .update('Test') - .update('123') - .verify(certPem, s1, 'base64'); -assert.strictEqual(verified, true, 'sign and verify (base 64)'); - -var s2 = crypto.createSign('RSA-SHA256') - .update('Test123') - .sign(keyPem, 'binary'); -var s2stream = crypto.createSign('RSA-SHA256'); -s2stream.end('Test123'); -s2stream = s2stream.sign(keyPem, 'binary'); -assert.equal(s2, s2stream, 'Stream produces same output'); - -var verified = crypto.createVerify('RSA-SHA256') - .update('Test') - .update('123') - .verify(certPem, s2, 'binary'); -assert.strictEqual(verified, true, 'sign and verify (binary)'); - -var verStream = crypto.createVerify('RSA-SHA256'); -verStream.write('Tes'); -verStream.write('t12'); -verStream.end('3'); -verified = verStream.verify(certPem, s2, 'binary'); -assert.strictEqual(verified, true, 'sign and verify (stream)'); - -var s3 = crypto.createSign('RSA-SHA1') - .update('Test123') - .sign(keyPem, 'buffer'); -var verified = crypto.createVerify('RSA-SHA1') - .update('Test') - .update('123') - .verify(certPem, s3); -assert.strictEqual(verified, true, 'sign and verify (buffer)'); - -var verStream = crypto.createVerify('RSA-SHA1'); -verStream.write('Tes'); -verStream.write('t12'); -verStream.end('3'); -verified = verStream.verify(certPem, s3); -assert.strictEqual(verified, true, 'sign and verify (stream)'); - - -function testCipher1(key) { - // Test encryption and decryption - var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - var cipher = crypto.createCipher('aes192', key); - - // encrypt plaintext which is in utf8 format - // to a ciphertext which will be in hex - var ciph = cipher.update(plaintext, 'utf8', 'hex'); - // Only use binary or hex, not base64. - ciph += cipher.final('hex'); - - var decipher = crypto.createDecipher('aes192', key); - var txt = decipher.update(ciph, 'hex', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption'); - - // streaming cipher interface - // NB: In real life, it's not guaranteed that you can get all of it - // in a single read() like this. But in this case, we know it's - // quite small, so there's no harm. - var cStream = crypto.createCipher('aes192', key); - cStream.end(plaintext); - ciph = cStream.read(); - - var dStream = crypto.createDecipher('aes192', key); - dStream.end(ciph); - txt = dStream.read().toString('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with streams'); -} - - -function testCipher2(key) { - // encryption and decryption with Base64 - // reported in https://github.com/joyent/node/issues/738 - var plaintext = - '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + - 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + - 'jAfaFg**'; - var cipher = crypto.createCipher('aes256', key); - - // encrypt plaintext which is in utf8 format - // to a ciphertext which will be in Base64 - var ciph = cipher.update(plaintext, 'utf8', 'base64'); - ciph += cipher.final('base64'); - - var decipher = crypto.createDecipher('aes256', key); - var txt = decipher.update(ciph, 'base64', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with Base64'); -} - - -function testCipher3(key, iv) { - // Test encyrption and decryption with explicit key and iv - var plaintext = - '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + - 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + - 'jAfaFg**'; - var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); - var ciph = cipher.update(plaintext, 'utf8', 'hex'); - ciph += cipher.final('hex'); - - var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); - var txt = decipher.update(ciph, 'hex', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); - - // streaming cipher interface - // NB: In real life, it's not guaranteed that you can get all of it - // in a single read() like this. But in this case, we know it's - // quite small, so there's no harm. - var cStream = crypto.createCipheriv('des-ede3-cbc', key, iv); - cStream.end(plaintext); - ciph = cStream.read(); - - var dStream = crypto.createDecipheriv('des-ede3-cbc', key, iv); - dStream.end(ciph); - txt = dStream.read().toString('utf8'); - - assert.equal(txt, plaintext, 'streaming cipher iv'); -} - - -function testCipher4(key, iv) { - // Test encyrption and decryption with explicit key and iv - var plaintext = - '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + - 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + - 'jAfaFg**'; - var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); - var ciph = cipher.update(plaintext, 'utf8', 'buffer'); - ciph = Buffer.concat([ciph, cipher.final('buffer')]); - - var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); - var txt = decipher.update(ciph, 'buffer', 'utf8'); - txt += decipher.final('utf8'); - - assert.equal(txt, plaintext, 'encryption and decryption with key and iv'); -} - - -testCipher1('MySecretKey123'); -testCipher1(new Buffer('MySecretKey123')); - -testCipher2('0123456789abcdef'); -testCipher2(new Buffer('0123456789abcdef')); - -testCipher3('0123456789abcd0123456789', '12345678'); -testCipher3('0123456789abcd0123456789', new Buffer('12345678')); -testCipher3(new Buffer('0123456789abcd0123456789'), '12345678'); -testCipher3(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); - -testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); - - -// update() should only take buffers / strings -assert.throws(function() { - crypto.createHash('sha1').update({foo: 'bar'}); -}, /buffer/); - - -// Test Diffie-Hellman with two parties sharing a secret, -// using various encodings as we go along -var dh1 = crypto.createDiffieHellman(256); -var p1 = dh1.getPrime('buffer'); -var dh2 = crypto.createDiffieHellman(p1, 'buffer'); -var key1 = dh1.generateKeys(); -var key2 = dh2.generateKeys('hex'); -var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); -var secret2 = dh2.computeSecret(key1, 'binary', 'buffer'); - -assert.equal(secret1, secret2.toString('base64')); -assert.equal(dh1.verifyError, 0); -assert.equal(dh2.verifyError, 0); - -assert.throws(function() { - crypto.createDiffieHellman([0x1, 0x2]); -}); - -assert.throws(function() { - crypto.createDiffieHellman(function() { }); -}); - -assert.throws(function() { - crypto.createDiffieHellman(/abc/); -}); - -assert.throws(function() { - crypto.createDiffieHellman({}); -}); - -// Create "another dh1" using generated keys from dh1, -// and compute secret again -var dh3 = crypto.createDiffieHellman(p1, 'buffer'); -var privkey1 = dh1.getPrivateKey(); -dh3.setPublicKey(key1); -dh3.setPrivateKey(privkey1); - -assert.deepEqual(dh1.getPrime(), dh3.getPrime()); -assert.deepEqual(dh1.getGenerator(), dh3.getGenerator()); -assert.deepEqual(dh1.getPublicKey(), dh3.getPublicKey()); -assert.deepEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); -assert.equal(dh3.verifyError, 0); - -var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); - -assert.equal(secret1, secret3); - -// Run this one twice to make sure that the dh3 clears its error properly -(function() { - var c = crypto.createDecipher('aes-128-ecb', ''); - assert.throws(function() { c.final('utf8') }, /wrong final block length/); -})(); - -assert.throws(function() { - dh3.computeSecret(''); -}, /key is too small/i); - -(function() { - var c = crypto.createDecipher('aes-128-ecb', ''); - assert.throws(function() { c.final('utf8') }, /wrong final block length/); -})(); - -// Create a shared using a DH group. -var alice = crypto.createDiffieHellmanGroup('modp5'); -var bob = crypto.createDiffieHellmanGroup('modp5'); -alice.generateKeys(); -bob.generateKeys(); -var aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); -var bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); -assert.equal(aSecret, bSecret); -assert.equal(alice.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); -assert.equal(bob.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - -// Ensure specific generator (buffer) works as expected. -var modp1 = crypto.createDiffieHellmanGroup('modp1'); -var modp1buf = new Buffer([ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, - 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, - 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, - 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, - 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, - 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, - 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, - 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, - 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff -]); -var exmodp1 = crypto.createDiffieHellman(modp1buf, new Buffer([2])); -modp1.generateKeys(); -exmodp1.generateKeys(); -var modp1Secret = modp1.computeSecret(exmodp1.getPublicKey()).toString('hex'); -var exmodp1Secret = exmodp1.computeSecret(modp1.getPublicKey()).toString('hex'); -assert.equal(modp1Secret, exmodp1Secret); -assert.equal(modp1.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); -assert.equal(exmodp1.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - - -// Ensure specific generator (string with encoding) works as expected. -var exmodp1_2 = crypto.createDiffieHellman(modp1buf, '02', 'hex'); -exmodp1_2.generateKeys(); -modp1Secret = modp1.computeSecret(exmodp1_2.getPublicKey()).toString('hex'); -var exmodp1_2Secret = exmodp1_2.computeSecret(modp1.getPublicKey()) - .toString('hex'); -assert.equal(modp1Secret, exmodp1_2Secret); -assert.equal(exmodp1_2.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - - -// Ensure specific generator (string without encoding) works as expected. -var exmodp1_3 = crypto.createDiffieHellman(modp1buf, '\x02'); -exmodp1_3.generateKeys(); -modp1Secret = modp1.computeSecret(exmodp1_3.getPublicKey()).toString('hex'); -var exmodp1_3Secret = exmodp1_3.computeSecret(modp1.getPublicKey()) - .toString('hex'); -assert.equal(modp1Secret, exmodp1_3Secret); -assert.equal(exmodp1_3.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - - -// Ensure specific generator (numeric) works as expected. -var exmodp1_4 = crypto.createDiffieHellman(modp1buf, 2); -exmodp1_4.generateKeys(); -modp1Secret = modp1.computeSecret(exmodp1_4.getPublicKey()).toString('hex'); -var exmodp1_4Secret = exmodp1_4.computeSecret(modp1.getPublicKey()) - .toString('hex'); -assert.equal(modp1Secret, exmodp1_4Secret); -assert.equal(exmodp1_4.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - - -var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + - '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + - '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + - 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; -var bad_dh = crypto.createDiffieHellman(p, 'hex'); -assert.equal(bad_dh.verifyError, constants.DH_NOT_SUITABLE_GENERATOR); - -// Test RSA encryption/decryption -(function() { - var input = 'I AM THE WALRUS'; - var bufferToEncrypt = new Buffer(input); - - var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); - - var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); - - var decryptedBufferWithPassword = crypto.privateDecrypt({ - key: rsaKeyPemEncrypted, - passphrase: 'password' - }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); - - encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); - - decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); - - encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); - - decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); - - assert.throws(function() { - crypto.privateDecrypt({ - key: rsaKeyPemEncrypted, - passphrase: 'wrong' - }, encryptedBuffer); - }); -})(); - -function test_rsa(padding) { - var input = new Buffer(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); - for (var i = 0; i < input.length; i++) - input[i] = (i * 7 + 11) & 0xff; - var bufferToEncrypt = new Buffer(input); - - padding = constants[padding]; - - var encryptedBuffer = crypto.publicEncrypt({ - key: rsaPubPem, - padding: padding - }, bufferToEncrypt); - - var decryptedBuffer = crypto.privateDecrypt({ - key: rsaKeyPem, - padding: padding - }, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); -} - -test_rsa('RSA_NO_PADDING'); -test_rsa('RSA_PKCS1_PADDING'); -test_rsa('RSA_PKCS1_OAEP_PADDING'); - -// Test RSA key signing/verification -var rsaSign = crypto.createSign('RSA-SHA1'); -var rsaVerify = crypto.createVerify('RSA-SHA1'); -assert.ok(rsaSign); -assert.ok(rsaVerify); - -rsaSign.update(rsaPubPem); -var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); -assert.equal(rsaSignature, - '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + - '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + - 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + - '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + - '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); - -rsaVerify.update(rsaPubPem); -assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); - -// Test RSA key signing/verification with encrypted key -rsaSign = crypto.createSign('RSA-SHA1'); -rsaSign.update(rsaPubPem); -assert.doesNotThrow(function() { - var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; - rsaSignature = rsaSign.sign(signOptions, 'hex'); -}); -assert.equal(rsaSignature, - '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + - '8f020d7e2688b122bfb54c724ac9ee169f83f66d2fe90abeb95e8' + - 'e1290e7e177152a4de3d944cf7d4883114a20ed0f78e70e25ef0f' + - '60f06b858e6af42a2f276ede95bbc6bc9a9bbdda15bd663186a6f' + - '40819a7af19e577bb2efa5e579a1f5ce8a0d4ca8b8f6'); - -rsaVerify = crypto.createVerify('RSA-SHA1'); -rsaVerify.update(rsaPubPem); -assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); - -rsaSign = crypto.createSign('RSA-SHA1'); -rsaSign.update(rsaPubPem); -assert.throws(function() { - var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; - rsaSign.sign(signOptions, 'hex'); -}); - -// -// Test RSA signing and verification -// -(function() { - var privateKey = fs.readFileSync( - common.fixturesDir + '/test_rsa_privkey_2.pem'); - - var publicKey = fs.readFileSync( - common.fixturesDir + '/test_rsa_pubkey_2.pem'); - - var input = 'I AM THE WALRUS'; - - var signature = - '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + - '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + - '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + - '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + - '0ddfb299bedeb1ad'; - - var sign = crypto.createSign('RSA-SHA256'); - sign.update(input); - - var output = sign.sign(privateKey, 'hex'); - assert.equal(output, signature); - - var verify = crypto.createVerify('RSA-SHA256'); - verify.update(input); - - assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); - - -// -// Test DSA signing and verification -// -(function() { - var input = 'I AM THE WALRUS'; - - // DSA signatures vary across runs so there is no static string to verify - // against - var sign = crypto.createSign('DSS1'); - sign.update(input); - var signature = sign.sign(dsaKeyPem, 'hex'); - - var verify = crypto.createVerify('DSS1'); - verify.update(input); - - assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); -})(); - - -// -// Test DSA signing and verification with encrypted key -// -(function() { - var input = 'I AM THE WALRUS'; - - var sign = crypto.createSign('DSS1'); - sign.update(input); - assert.throws(function() { - sign.sign({ key: dsaKeyPemEncrypted, passphrase: 'wrong' }, 'hex'); - }); - - // DSA signatures vary across runs so there is no static string to verify - // against - var sign = crypto.createSign('DSS1'); - sign.update(input); - - var signature; - assert.doesNotThrow(function() { - var signOptions = { key: dsaKeyPemEncrypted, passphrase: 'password' }; - signature = sign.sign(signOptions, 'hex'); - }); - - var verify = crypto.createVerify('DSS1'); - verify.update(input); - - assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); -})(); - - -// -// Test PBKDF2 with RFC 6070 test vectors (except #4) -// -function testPBKDF2(password, salt, iterations, keylen, expected) { - var actual = crypto.pbkdf2Sync(password, salt, iterations, keylen); - assert.equal(actual.toString('binary'), expected); - - crypto.pbkdf2(password, salt, iterations, keylen, function(err, actual) { - assert.equal(actual.toString('binary'), expected); - }); -} - - -testPBKDF2('password', 'salt', 1, 20, - '\x0c\x60\xc8\x0f\x96\x1f\x0e\x71\xf3\xa9\xb5\x24' + - '\xaf\x60\x12\x06\x2f\xe0\x37\xa6'); - -testPBKDF2('password', 'salt', 2, 20, - '\xea\x6c\x01\x4d\xc7\x2d\x6f\x8c\xcd\x1e\xd9\x2a' + - '\xce\x1d\x41\xf0\xd8\xde\x89\x57'); - -testPBKDF2('password', 'salt', 4096, 20, - '\x4b\x00\x79\x01\xb7\x65\x48\x9a\xbe\xad\x49\xd9\x26' + - '\xf7\x21\xd0\x65\xa4\x29\xc1'); - -testPBKDF2('passwordPASSWORDpassword', - 'saltSALTsaltSALTsaltSALTsaltSALTsalt', - 4096, - 25, - '\x3d\x2e\xec\x4f\xe4\x1c\x84\x9b\x80\xc8\xd8\x36\x62' + - '\xc0\xe4\x4a\x8b\x29\x1a\x96\x4c\xf2\xf0\x70\x38'); - -testPBKDF2('pass\0word', 'sa\0lt', 4096, 16, - '\x56\xfa\x6a\xa7\x55\x48\x09\x9d\xcc\x37\xd7\xf0\x34' + - '\x25\xe0\xc3'); - -(function() { - var expected = - '64c486c55d30d4c5a079b8823b7d7cb37ff0556f537da8410233bcec330ed956'; - var key = crypto.pbkdf2Sync('password', 'salt', 32, 32, 'sha256'); - assert.equal(key.toString('hex'), expected); - - crypto.pbkdf2('password', 'salt', 32, 32, 'sha256', common.mustCall(ondone)); - function ondone(err, key) { - if (err) throw err; - assert.equal(key.toString('hex'), expected); - } -})(); - -function assertSorted(list) { - // Array#sort() modifies the list in place so make a copy. - var sorted = util._extend([], list).sort(); - assert.deepEqual(list, sorted); -} - -// Assume that we have at least AES-128-CBC. -assert.notEqual(0, crypto.getCiphers().length); -assert.notEqual(-1, crypto.getCiphers().indexOf('aes-128-cbc')); -assert.equal(-1, crypto.getCiphers().indexOf('AES-128-CBC')); -assertSorted(crypto.getCiphers()); - -// Assume that we have at least AES256-SHA. -var tls = require('tls'); -assert.notEqual(0, tls.getCiphers().length); -assert.notEqual(-1, tls.getCiphers().indexOf('aes256-sha')); -assert.equal(-1, tls.getCiphers().indexOf('AES256-SHA')); -assertSorted(tls.getCiphers()); - -// Assert that we have sha and sha1 but not SHA and SHA1. -assert.notEqual(0, crypto.getHashes().length); -assert.notEqual(-1, crypto.getHashes().indexOf('sha1')); -assert.notEqual(-1, crypto.getHashes().indexOf('sha')); -assert.equal(-1, crypto.getHashes().indexOf('SHA1')); -assert.equal(-1, crypto.getHashes().indexOf('SHA')); -assert.notEqual(-1, crypto.getHashes().indexOf('RSA-SHA1')); -assert.equal(-1, crypto.getHashes().indexOf('rsa-sha1')); -assertSorted(crypto.getHashes()); - -// Base64 padding regression test, see #4837. -(function() { - var c = crypto.createCipher('aes-256-cbc', 'secret'); - var s = c.update('test', 'utf8', 'base64') + c.final('base64'); - assert.equal(s, '375oxUQCIocvxmC5At+rvA=='); -})(); - -// Error path should not leak memory (check with valgrind). -assert.throws(function() { - crypto.pbkdf2('password', 'salt', 1, 20, null); -}); - -// Calling Cipher.final() or Decipher.final() twice should error but -// not assert. See #4886. -(function() { - var c = crypto.createCipher('aes-256-cbc', 'secret'); - try { c.final('xxx') } catch (e) { /* Ignore. */ } - try { c.final('xxx') } catch (e) { /* Ignore. */ } - try { c.final('xxx') } catch (e) { /* Ignore. */ } - var d = crypto.createDecipher('aes-256-cbc', 'secret'); - try { d.final('xxx') } catch (e) { /* Ignore. */ } - try { d.final('xxx') } catch (e) { /* Ignore. */ } - try { d.final('xxx') } catch (e) { /* Ignore. */ } -})(); - -// Regression test for #5482: string to Cipher#update() should not assert. -(function() { - var c = crypto.createCipher('aes192', '0123456789abcdef'); - c.update('update'); - c.final(); -})(); - -// #5655 regression tests, 'utf-8' and 'utf8' are identical. -(function() { - var c = crypto.createCipher('aes192', '0123456789abcdef'); - c.update('update', ''); // Defaults to "utf8". - c.final('utf-8'); // Should not throw. - - c = crypto.createCipher('aes192', '0123456789abcdef'); - c.update('update', 'utf8'); - c.final('utf-8'); // Should not throw. - - c = crypto.createCipher('aes192', '0123456789abcdef'); - c.update('update', 'utf-8'); - c.final('utf8'); // Should not throw. -})(); - -// Regression tests for #5725: hex input that's not a power of two should -// throw, not assert in C++ land. -assert.throws(function() { - crypto.createCipher('aes192', 'test').update('0', 'hex'); -}, /Bad input string/); - -assert.throws(function() { - crypto.createDecipher('aes192', 'test').update('0', 'hex'); -}, /Bad input string/); - -assert.throws(function() { - crypto.createHash('sha1').update('0', 'hex'); -}, /Bad input string/); - -assert.throws(function() { - crypto.createSign('RSA-SHA1').update('0', 'hex'); -}, /Bad input string/); - -assert.throws(function() { - crypto.createVerify('RSA-SHA1').update('0', 'hex'); -}, /Bad input string/); - -assert.throws(function() { - var private = [ - '-----BEGIN RSA PRIVATE KEY-----', - 'MIGrAgEAAiEA+3z+1QNF2/unumadiwEr+C5vfhezsb3hp4jAnCNRpPcCAwEAAQIgQNriSQK4', - 'EFwczDhMZp2dvbcz7OUUyt36z3S4usFPHSECEQD/41K7SujrstBfoCPzwC1xAhEA+5kt4BJy', - 'eKN7LggbF3Dk5wIQN6SL+fQ5H/+7NgARsVBp0QIRANxYRukavs4QvuyNhMx+vrkCEQCbf6j/', - 'Ig6/HueCK/0Jkmp+', - '-----END RSA PRIVATE KEY-----', - '' - ].join('\n'); - crypto.createSign('RSA-SHA256').update('test').sign(private); -}, /RSA_sign:digest too big for rsa key/); - -// Make sure memory isn't released before being returned -console.log(crypto.randomBytes(16)); - -// Test ECDH -var ecdh1 = crypto.createECDH('prime256v1'); -var ecdh2 = crypto.createECDH('prime256v1'); -var key1 = ecdh1.generateKeys(); -var key2 = ecdh2.generateKeys('hex'); -var secret1 = ecdh1.computeSecret(key2, 'hex', 'base64'); -var secret2 = ecdh2.computeSecret(key1, 'binary', 'buffer'); - -assert.equal(secret1, secret2.toString('base64')); - -// Point formats -assert.equal(ecdh1.getPublicKey('buffer', 'uncompressed')[0], 4); -var firstByte = ecdh1.getPublicKey('buffer', 'compressed')[0]; -assert(firstByte === 2 || firstByte === 3); -var firstByte = ecdh1.getPublicKey('buffer', 'hybrid')[0]; -assert(firstByte === 6 || firstByte === 7); - -// ECDH should check that point is on curve -var ecdh3 = crypto.createECDH('secp256k1'); -var key3 = ecdh3.generateKeys(); - -assert.throws(function() { - var secret3 = ecdh2.computeSecret(key3, 'binary', 'buffer'); -}); - -// ECDH should allow .setPrivateKey()/.setPublicKey() -var ecdh4 = crypto.createECDH('prime256v1'); - -ecdh4.setPrivateKey(ecdh1.getPrivateKey()); -ecdh4.setPublicKey(ecdh1.getPublicKey()); - -assert.throws(function() { - ecdh4.setPublicKey(ecdh3.getPublicKey()); -}); diff --git a/test/simple/test-debug-args.js b/test/simple/test-debug-args.js deleted file mode 100644 index 51eaa801d..000000000 --- a/test/simple/test-debug-args.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Flags: --debugger - -var common = require('../common'); -var assert = require('assert'); - -assert.notEqual(process.execArgv.indexOf('--debugger'), -1); diff --git a/test/simple/test-debug-cluster.js b/test/simple/test-debug-cluster.js deleted file mode 100644 index c0963c35a..000000000 --- a/test/simple/test-debug-cluster.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -var args = ['--debug', common.fixturesDir + '/clustered-server/app.js' ]; -var child = spawn(process.execPath, args); -var outputLines = []; - -child.stderr.on('data', function(data) { - var lines = data.toString().replace(/\r/g, '').trim().split('\n'); - var line = lines[0]; - - lines.forEach(function(ln) { console.log('> ' + ln) } ); - - if (line === 'all workers are running') { - assertOutputLines(); - process.exit(); - } else { - outputLines = outputLines.concat(lines); - } -}); - -process.on('exit', function onExit() { - child.kill(); -}); - -var assertOutputLines = common.mustCall(function() { - var expectedLines = [ - 'Debugger listening on port ' + 5858, - 'Debugger listening on port ' + 5859, - 'Debugger listening on port ' + 5860, - ]; - - // Do not assume any particular order of output messages, - // since workers can take different amout of time to - // start up - outputLines.sort(); - - assert.equal(outputLines.length, expectedLines.length) - for (var i = 0; i < expectedLines.length; i++) - assert.equal(outputLines[i], expectedLines[i]); -}); diff --git a/test/simple/test-debug-port-cluster.js b/test/simple/test-debug-port-cluster.js deleted file mode 100644 index 34ae3a029..000000000 --- a/test/simple/test-debug-port-cluster.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -var port = common.PORT + 1337; - -var args = [ - '--debug=' + port, - common.fixturesDir + '/clustered-server/app.js' -]; - -var child = spawn(process.execPath, args); -var outputLines = []; - -child.stderr.on('data', function(data) { - var lines = data.toString().replace(/\r/g, '').trim().split('\n'); - var line = lines[0]; - - lines.forEach(function(ln) { console.log('> ' + ln) } ); - - if (line === 'all workers are running') { - assertOutputLines(); - process.exit(); - } else { - outputLines = outputLines.concat(lines); - } -}); - -process.on('exit', function onExit() { - child.kill(); -}); - -var assertOutputLines = common.mustCall(function() { - var expectedLines = [ - 'Debugger listening on port ' + port, - 'Debugger listening on port ' + (port+1), - 'Debugger listening on port ' + (port+2), - ]; - - // Do not assume any particular order of output messages, - // since workers can take different amout of time to - // start up - outputLines.sort(); - - assert.equal(outputLines.length, expectedLines.length) - for (var i = 0; i < expectedLines.length; i++) - assert.equal(outputLines[i], expectedLines[i]); -}); diff --git a/test/simple/test-debug-port-from-cmdline.js b/test/simple/test-debug-port-from-cmdline.js deleted file mode 100644 index db0f1b382..000000000 --- a/test/simple/test-debug-port-from-cmdline.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -var debugPort = common.PORT; -var args = ['--debug-port=' + debugPort]; -var child = spawn(process.execPath, args); - -child.stderr.on('data', function(data) { - var lines = data.toString().replace(/\r/g, '').trim().split('\n'); - lines.forEach(processStderrLine); -}); - -setTimeout(testTimedOut, 3000); -function testTimedOut() { - assert(false, 'test timed out.'); -} - -// Give the child process small amout of time to start -setTimeout(function() { - process._debugProcess(child.pid); -}, 100); - -process.on('exit', function() { - child.kill(); -}); - -var outputLines = []; -function processStderrLine(line) { - console.log('> ' + line); - outputLines.push(line); - - if (/Debugger listening/.test(line)) { - assertOutputLines(); - process.exit(); - } -} - -function assertOutputLines() { - var expectedLines = [ - 'Starting debugger agent.', - 'Debugger listening on port ' + debugPort - ]; - - assert.equal(outputLines.length, expectedLines.length); - for (var i = 0; i < expectedLines.length; i++) - assert.equal(outputLines[i], expectedLines[i]); - -} diff --git a/test/simple/test-debug-signal-cluster.js b/test/simple/test-debug-signal-cluster.js deleted file mode 100644 index cd57e548a..000000000 --- a/test/simple/test-debug-signal-cluster.js +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -var args = [ common.fixturesDir + '/clustered-server/app.js' ]; -var child = spawn(process.execPath, args, { - stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ] -}); -var outputLines = []; -var outputTimerId; -var waitingForDebuggers = false; - -var pids = null; - -child.stderr.on('data', function(data) { - var lines = data.toString().replace(/\r/g, '').trim().split('\n'); - var line = lines[0]; - - lines.forEach(function(ln) { console.log('> ' + ln) } ); - - if (outputTimerId !== undefined) - clearTimeout(outputTimerId); - - if (waitingForDebuggers) { - outputLines = outputLines.concat(lines); - outputTimerId = setTimeout(onNoMoreLines, 800); - } else if (line === 'all workers are running') { - child.on('message', function(msg) { - if (msg.type !== 'pids') - return; - - pids = msg.pids; - console.error('got pids %j', pids); - - waitingForDebuggers = true; - process._debugProcess(child.pid); - }); - - child.send({ - type: 'getpids' - }); - } -}); - -function onNoMoreLines() { - assertOutputLines(); - process.exit(); -} - -setTimeout(function testTimedOut() { - assert(false, 'test timed out.'); -}, 6000); - -process.on('exit', function onExit() { - // Kill processes in reverse order to avoid timing problems on Windows where - // the parent process is killed before the children. - pids.reverse().forEach(function(pid) { - process.kill(pid); - }); -}); - -function assertOutputLines() { - var expectedLines = [ - 'Starting debugger agent.', - 'Debugger listening on port ' + 5858, - 'Starting debugger agent.', - 'Debugger listening on port ' + 5859, - 'Starting debugger agent.', - 'Debugger listening on port ' + 5860, - ]; - - // Do not assume any particular order of output messages, - // since workers can take different amout of time to - // start up - outputLines.sort(); - expectedLines.sort(); - - assert.equal(outputLines.length, expectedLines.length); - for (var i = 0; i < expectedLines.length; i++) - assert.equal(outputLines[i], expectedLines[i]); -} diff --git a/test/simple/test-delayed-require.js b/test/simple/test-delayed-require.js deleted file mode 100644 index 31c324976..000000000 --- a/test/simple/test-delayed-require.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var a; -setTimeout(function() { - a = require('../fixtures/a'); -}, 50); - -process.on('exit', function() { - assert.equal(true, 'A' in a); - assert.equal('A', a.A()); - assert.equal('D', a.D()); -}); diff --git a/test/simple/test-deprecation-flags.js b/test/simple/test-deprecation-flags.js deleted file mode 100644 index 3d50c097f..000000000 --- a/test/simple/test-deprecation-flags.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var execFile = require('child_process').execFile; -var depmod = require.resolve('../fixtures/deprecated.js'); -var node = process.execPath; - -var normal = [depmod]; -var noDep = ['--no-deprecation', depmod]; -var traceDep = ['--trace-deprecation', depmod]; - -execFile(node, normal, function(er, stdout, stderr) { - console.error('normal: show deprecation warning'); - assert.equal(er, null); - assert.equal(stdout, ''); - assert.equal(stderr, 'util.p: Use console.error() instead\n\'This is deprecated\'\n'); - console.log('normal ok'); -}); - -execFile(node, noDep, function(er, stdout, stderr) { - console.error('--no-deprecation: silence deprecations'); - assert.equal(er, null); - assert.equal(stdout, ''); - assert.equal(stderr, '\'This is deprecated\'\n'); - console.log('silent ok'); -}); - -execFile(node, traceDep, function(er, stdout, stderr) { - console.error('--trace-deprecation: show stack'); - assert.equal(er, null); - assert.equal(stdout, ''); - var stack = stderr.trim().split('\n'); - // just check the top and bottom. - assert.equal(stack[0], 'Trace: util.p: Use console.error() instead'); - assert.equal(stack.pop(), '\'This is deprecated\''); - console.log('trace ok'); -}); diff --git a/test/simple/test-dgram-address.js b/test/simple/test-dgram-address.js deleted file mode 100644 index 30d8eb0e1..000000000 --- a/test/simple/test-dgram-address.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -// IPv4 Test -var localhost_ipv4 = '127.0.0.1'; -var socket_ipv4 = dgram.createSocket('udp4'); -var family_ipv4 = 'IPv4'; - -socket_ipv4.on('listening', function() { - var address_ipv4 = socket_ipv4.address(); - assert.strictEqual(address_ipv4.address, localhost_ipv4); - assert.strictEqual(address_ipv4.port, common.PORT); - assert.strictEqual(address_ipv4.family, family_ipv4); - socket_ipv4.close(); -}); - -socket_ipv4.on('error', function(e) { - console.log('Error on udp4 socket. ' + e.toString()); - socket_ipv4.close(); -}); - -socket_ipv4.bind(common.PORT, localhost_ipv4); - -// IPv6 Test -var localhost_ipv6 = '::1'; -var socket_ipv6 = dgram.createSocket('udp6'); -var family_ipv6 = 'IPv6'; - -socket_ipv6.on('listening', function() { - var address_ipv6 = socket_ipv6.address(); - assert.strictEqual(address_ipv6.address, localhost_ipv6); - assert.strictEqual(address_ipv6.port, common.PORT); - assert.strictEqual(address_ipv6.family, family_ipv6); - socket_ipv6.close(); -}); - -socket_ipv6.on('error', function(e) { - console.log('Error on udp6 socket. ' + e.toString()); - socket_ipv6.close(); -}); - -socket_ipv6.bind(common.PORT, localhost_ipv6); diff --git a/test/simple/test-dgram-bind-default-address.js b/test/simple/test-dgram-bind-default-address.js deleted file mode 100644 index e7b65c57b..000000000 --- a/test/simple/test-dgram-bind-default-address.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -dgram.createSocket('udp4').bind(common.PORT + 0, common.mustCall(function() { - assert.equal(this.address().port, common.PORT + 0); - assert.equal(this.address().address, '0.0.0.0'); - this.close(); -})); - -if (!common.hasIPv6) { - console.error('Skipping udp6 part of test, no IPv6 support'); - return; -} - -dgram.createSocket('udp6').bind(common.PORT + 1, common.mustCall(function() { - assert.equal(this.address().port, common.PORT + 1); - var address = this.address().address; - if (address === '::ffff:0.0.0.0') - address = '::'; - assert.equal(address, '::'); - this.close(); -})); diff --git a/test/simple/test-dgram-bind-shared-ports.js b/test/simple/test-dgram-bind-shared-ports.js deleted file mode 100644 index c9e22b592..000000000 --- a/test/simple/test-dgram-bind-shared-ports.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var dgram = require('dgram'); - -// TODO XXX FIXME when windows supports clustered dgram ports re-enable this -// test -if (process.platform == 'win32') - process.exit(0); - -function noop() {} - -if (cluster.isMaster) { - var worker1 = cluster.fork(); - - worker1.on('message', function(msg) { - assert.equal(msg, 'success'); - var worker2 = cluster.fork(); - - worker2.on('message', function(msg) { - assert.equal(msg, 'socket2:EADDRINUSE'); - worker1.kill(); - worker2.kill(); - }); - }); -} else { - var socket1 = dgram.createSocket('udp4', noop); - var socket2 = dgram.createSocket('udp4', noop); - - socket1.on('error', function(err) { - // no errors expected - process.send('socket1:' + err.code); - }); - - socket2.on('error', function(err) { - // an error is expected on the second worker - process.send('socket2:' + err.code); - }); - - socket1.bind({ - address: 'localhost', - port: common.PORT, - exclusive: false - }, function() { - socket2.bind({port: common.PORT + 1, exclusive: true}, function() { - // the first worker should succeed - process.send('success'); - }); - }); -} diff --git a/test/simple/test-dgram-bind.js b/test/simple/test-dgram-bind.js deleted file mode 100644 index 8ee67637f..000000000 --- a/test/simple/test-dgram-bind.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -var socket = dgram.createSocket('udp4'); - -socket.on('listening', function () { - socket.close(); -}); - -socket.bind(); // should not throw diff --git a/test/simple/test-dgram-broadcast-multi-process.js b/test/simple/test-dgram-broadcast-multi-process.js deleted file mode 100644 index 4d9eebc10..000000000 --- a/test/simple/test-dgram-broadcast-multi-process.js +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - dgram = require('dgram'), - util = require('util'), - networkInterfaces = require('os').networkInterfaces(), - Buffer = require('buffer').Buffer, - fork = require('child_process').fork, - LOCAL_BROADCAST_HOST = '255.255.255.255', - TIMEOUT = 5000, - messages = [ - new Buffer('First message to send'), - new Buffer('Second message to send'), - new Buffer('Third message to send'), - new Buffer('Fourth message to send') - ]; - -// take the first non-internal interface as the address for binding -get_bindAddress: for (var name in networkInterfaces) { - var interfaces = networkInterfaces[name]; - for(var i = 0; i < interfaces.length; i++) { - var localInterface = interfaces[i]; - if (!localInterface.internal && localInterface.family === 'IPv4') { - var bindAddress = localInterface.address; - break get_bindAddress; - } - } -} -assert.ok(bindAddress); - -if (process.argv[2] !== 'child') { - var workers = {}, - listeners = 3, - listening = 0, - dead = 0, - i = 0, - done = 0, - timer = null; - - //exit the test if it doesn't succeed within TIMEOUT - timer = setTimeout(function() { - console.error('[PARENT] Responses were not received within %d ms.', - TIMEOUT); - console.error('[PARENT] Fail'); - - killChildren(workers); - - process.exit(1); - }, TIMEOUT); - - //launch child processes - for (var x = 0; x < listeners; x++) { - (function() { - var worker = fork(process.argv[1], ['child']); - workers[worker.pid] = worker; - - worker.messagesReceived = []; - - //handle the death of workers - worker.on('exit', function(code, signal) { - // don't consider this the true death if the worker - // has finished successfully - // or if the exit code is 0 - if (worker.isDone || code == 0) { - return; - } - - dead += 1; - console.error('[PARENT] Worker %d died. %d dead of %d', - worker.pid, - dead, - listeners); - - if (dead === listeners) { - console.error('[PARENT] All workers have died.'); - console.error('[PARENT] Fail'); - - killChildren(workers); - - process.exit(1); - } - }); - - worker.on('message', function(msg) { - if (msg.listening) { - listening += 1; - - if (listening === listeners) { - //all child process are listening, so start sending - sendSocket.sendNext(); - } - } - else if (msg.message) { - worker.messagesReceived.push(msg.message); - - if (worker.messagesReceived.length === messages.length) { - done += 1; - worker.isDone = true; - console.error('[PARENT] %d received %d messages total.', - worker.pid, - worker.messagesReceived.length); - } - - if (done === listeners) { - console.error('[PARENT] All workers have received the ' + - 'required number of ' + - 'messages. Will now compare.'); - - Object.keys(workers).forEach(function(pid) { - var worker = workers[pid]; - - var count = 0; - - worker.messagesReceived.forEach(function(buf) { - for (var i = 0; i < messages.length; ++i) { - if (buf.toString() === messages[i].toString()) { - count++; - break; - } - } - }); - - console.error('[PARENT] %d received %d matching messges.', - worker.pid, - count); - - assert.equal(count, messages.length, - 'A worker received an invalid multicast message'); - }); - - clearTimeout(timer); - console.error('[PARENT] Success'); - killChildren(workers); - } - } - }); - })(x); - } - - var sendSocket = dgram.createSocket({ - type: 'udp4', - reuseAddr: true - }); - - // bind the address explicitly for sending - // INADDR_BROADCAST to only one interface - sendSocket.bind(common.PORT, bindAddress); - sendSocket.on('listening', function () { - sendSocket.setBroadcast(true); - }); - - sendSocket.on('close', function() { - console.error('[PARENT] sendSocket closed'); - }); - - sendSocket.sendNext = function() { - var buf = messages[i++]; - - if (!buf) { - try { sendSocket.close(); } catch (e) {} - return; - } - - sendSocket.send(buf, 0, buf.length, - common.PORT, LOCAL_BROADCAST_HOST, function(err) { - - if (err) throw err; - - console.error('[PARENT] sent %s to %s:%s', - util.inspect(buf.toString()), - LOCAL_BROADCAST_HOST, common.PORT); - - process.nextTick(sendSocket.sendNext); - }); - }; - - function killChildren(children) { - Object.keys(children).forEach(function(key) { - var child = children[key]; - child.kill(); - }); - } -} - -if (process.argv[2] === 'child') { - var receivedMessages = []; - var listenSocket = dgram.createSocket({ - type: 'udp4', - reuseAddr: true - }); - - listenSocket.on('message', function(buf, rinfo) { - // receive udp messages only sent from parent - if (rinfo.address !== bindAddress) return; - - console.error('[CHILD] %s received %s from %j', - process.pid, - util.inspect(buf.toString()), - rinfo); - - receivedMessages.push(buf); - - process.send({ message: buf.toString() }); - - if (receivedMessages.length == messages.length) { - process.nextTick(function() { - listenSocket.close(); - }); - } - }); - - listenSocket.on('close', function() { - //HACK: Wait to exit the process to ensure that the parent - //process has had time to receive all messages via process.send() - //This may be indicitave of some other issue. - setTimeout(function() { - process.exit(); - }, 1000); - }); - - listenSocket.on('listening', function() { - process.send({ listening: true }); - }); - - listenSocket.bind(common.PORT); -} diff --git a/test/simple/test-dgram-bytes-length.js b/test/simple/test-dgram-bytes-length.js deleted file mode 100644 index 4e90f78c8..000000000 --- a/test/simple/test-dgram-bytes-length.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -var message = new Buffer('Some bytes'); -var client = dgram.createSocket('udp4'); -client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) { - assert.strictEqual(bytes, message.length); - client.close(); -}); diff --git a/test/simple/test-dgram-close.js b/test/simple/test-dgram-close.js deleted file mode 100644 index 77af6f13b..000000000 --- a/test/simple/test-dgram-close.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Ensure that if a dgram socket is closed before the DNS lookup completes, it -// won't crash. - -var assert = require('assert'), - common = require('../common'), - dgram = require('dgram'); - -var buf = new Buffer(1024); -buf.fill(42); - -var socket = dgram.createSocket('udp4'); -var handle = socket._handle; -socket.send(buf, 0, buf.length, common.PORT, 'localhost'); -socket.close(); -socket = null; - -// Verify that accessing handle after closure doesn't throw -setImmediate(function() { - setImmediate(function() { - console.log('Handle fd is: ', handle.fd); - }); -}); diff --git a/test/simple/test-dgram-empty-packet.js b/test/simple/test-dgram-empty-packet.js deleted file mode 100644 index 812e88a3b..000000000 --- a/test/simple/test-dgram-empty-packet.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var dgram = require('dgram'); -var callbacks = 0; -var client; -var timer; - -if (process.platform === 'darwin') { - console.error('Test is disabled due to 17894467 Apple bug'); - return; -} - -client = dgram.createSocket('udp4'); - -client.bind(common.PORT); - -function callback() { - callbacks++; - if (callbacks == 2) { - clearTimeout(timer); - client.close(); - } else if (callbacks > 2) { - throw new Error("the callbacks should be called only two times"); - } -} - -client.on('message', function (buffer, bytes) { - callback(); -}); - -client.send(new Buffer(1), 0, 0, common.PORT, "127.0.0.1", function (err, len) { - callback(); -}); - -timer = setTimeout(function() { - throw new Error('Timeout'); -}, 200); diff --git a/test/simple/test-dgram-implicit-bind.js b/test/simple/test-dgram-implicit-bind.js deleted file mode 100644 index 6039629c4..000000000 --- a/test/simple/test-dgram-implicit-bind.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -var source = dgram.createSocket('udp4'); -var target = dgram.createSocket('udp4'); -var messages = 0; - -process.on('exit', function() { - assert.equal(messages, 2); -}); - -target.on('message', function(buf) { - if (buf.toString() === 'abc') ++messages; - if (buf.toString() === 'def') ++messages; - if (messages === 2) { - source.close(); - target.close(); - } -}); - -target.on('listening', function() { - // Second .send() call should not throw a bind error. - source.send(Buffer('abc'), 0, 3, common.PORT, '127.0.0.1'); - source.send(Buffer('def'), 0, 3, common.PORT, '127.0.0.1'); -}); - -target.bind(common.PORT); diff --git a/test/simple/test-dgram-listen-after-bind.js b/test/simple/test-dgram-listen-after-bind.js deleted file mode 100644 index e5f1c4d65..000000000 --- a/test/simple/test-dgram-listen-after-bind.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -var socket = dgram.createSocket('udp4'); - -socket.bind(); - -var fired = false; -var timer = setTimeout(function () { - socket.close(); -}, 100); - -socket.on('listening', function () { - clearTimeout(timer); - fired = true; - socket.close(); -}); - -socket.on('close', function () { - assert(fired, 'listening should fire after bind'); -}); diff --git a/test/simple/test-dgram-msgsize.js b/test/simple/test-dgram-msgsize.js deleted file mode 100644 index 03f9cb532..000000000 --- a/test/simple/test-dgram-msgsize.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -// Send a too big datagram. The destination doesn't matter because it's -// not supposed to get sent out anyway. -var buf = Buffer(256 * 1024); -var sock = dgram.createSocket('udp4'); -sock.send(buf, 0, buf.length, 12345, '127.0.0.1', common.mustCall(cb)); -function cb(err) { - assert(err instanceof Error); - assert.equal(err.code, 'EMSGSIZE'); - sock.close(); -} diff --git a/test/simple/test-dgram-multicast-setTTL.js b/test/simple/test-dgram-multicast-setTTL.js deleted file mode 100644 index 2ef0c167a..000000000 --- a/test/simple/test-dgram-multicast-setTTL.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - dgram = require('dgram'), - thrown = false, - socket = dgram.createSocket('udp4'); - -socket.bind(common.PORT); -socket.on('listening', function () { - socket.setMulticastTTL(16); - - //Try to set an invalid TTL (valid ttl is > 0 and < 256) - try { - socket.setMulticastTTL(1000); - } catch (e) { - thrown = true; - } - - assert(thrown, 'Setting an invalid multicast TTL should throw some error'); - - //close the socket - socket.close(); -}); diff --git a/test/simple/test-dgram-oob-buffer.js b/test/simple/test-dgram-oob-buffer.js deleted file mode 100644 index 061c8417c..000000000 --- a/test/simple/test-dgram-oob-buffer.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Some operating systems report errors when an UDP message is sent to an -// unreachable host. This error can be reported by sendto() and even by -// recvfrom(). Node should not propagate this error to the user. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -var socket = dgram.createSocket('udp4'); -var buf = Buffer([1,2,3,4]); - -function ok() {} -socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no -socket.send(buf, 0, 4, common.PORT, '127.0.0.1', ok); -socket.send(buf, 1, 3, common.PORT, '127.0.0.1', ok); -socket.send(buf, 3, 1, common.PORT, '127.0.0.1', ok); -// Since length of zero means nothing, don't error despite OOB. -socket.send(buf, 4, 0, common.PORT, '127.0.0.1', ok); - -assert.throws(function() { - socket.send(buf, 0, 5, common.PORT, '127.0.0.1', assert.fail); -}); -assert.throws(function() { - socket.send(buf, 2, 3, common.PORT, '127.0.0.1', assert.fail); -}); -assert.throws(function() { - socket.send(buf, 4, 4, common.PORT, '127.0.0.1', assert.fail); -}); -assert.throws(function() { - socket.send('abc', 4, 1, common.PORT, '127.0.0.1', assert.fail); -}); -assert.throws(function() { - socket.send('abc', 0, 4, common.PORT, '127.0.0.1', assert.fail); -}); -assert.throws(function() { - socket.send('abc', -1, 2, common.PORT, '127.0.0.1', assert.fail); -}); - -socket.close(); // FIXME should not be necessary diff --git a/test/simple/test-dgram-pingpong.js b/test/simple/test-dgram-pingpong.js deleted file mode 100644 index 992153293..000000000 --- a/test/simple/test-dgram-pingpong.js +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var Buffer = require('buffer').Buffer; -var dgram = require('dgram'); - -var debug = false; -var tests_run = 0; - -function pingPongTest(port, host) { - var callbacks = 0; - var N = 500; - var count = 0; - var sent_final_ping = false; - - var server = dgram.createSocket('udp4', function(msg, rinfo) { - if (debug) console.log('server got: ' + msg + - ' from ' + rinfo.address + ':' + rinfo.port); - - if (/PING/.exec(msg)) { - var buf = new Buffer(4); - buf.write('PONG'); - server.send(buf, 0, buf.length, - rinfo.port, rinfo.address, - function(err, sent) { - callbacks++; - }); - } - }); - - server.on('error', function(e) { - throw e; - }); - - server.on('listening', function() { - console.log('server listening on ' + port + ' ' + host); - - var buf = new Buffer('PING'), - client = dgram.createSocket('udp4'); - - client.on('message', function(msg, rinfo) { - if (debug) console.log('client got: ' + msg + - ' from ' + rinfo.address + ':' + rinfo.port); - assert.equal('PONG', msg.toString('ascii')); - - count += 1; - - if (count < N) { - client.send(buf, 0, buf.length, port, 'localhost'); - } else { - sent_final_ping = true; - client.send(buf, 0, buf.length, port, 'localhost', function() { - client.close(); - }); - } - }); - - client.on('close', function() { - console.log('client has closed, closing server'); - assert.equal(N, count); - tests_run += 1; - server.close(); - assert.equal(N - 1, callbacks); - }); - - client.on('error', function(e) { - throw e; - }); - - console.log('Client sending to ' + port + ', localhost ' + buf); - client.send(buf, 0, buf.length, port, 'localhost', function(err, bytes) { - if (err) { - throw err; - } - console.log('Client sent ' + bytes + ' bytes'); - }); - count += 1; - }); - server.bind(port, host); -} - -// All are run at once, so run on different ports -pingPongTest(common.PORT + 0, 'localhost'); -pingPongTest(common.PORT + 1, 'localhost'); -pingPongTest(common.PORT + 2); -//pingPongTest('/tmp/pingpong.sock'); - -process.on('exit', function() { - assert.equal(3, tests_run); - console.log('done'); -}); diff --git a/test/simple/test-dgram-ref.js b/test/simple/test-dgram-ref.js deleted file mode 100644 index ebbbac2fc..000000000 --- a/test/simple/test-dgram-ref.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var dgram = require('dgram'); - -// should not hang, see #1282 -dgram.createSocket('udp4'); -dgram.createSocket('udp6'); diff --git a/test/simple/test-dgram-regress-4496.js b/test/simple/test-dgram-regress-4496.js deleted file mode 100644 index e45824a10..000000000 --- a/test/simple/test-dgram-regress-4496.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Remove this test once we support sending strings. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -// Should throw but not crash. -var socket = dgram.createSocket('udp4'); -assert.throws(function() { socket.send(true, 0, 1, 1, 'host') }, TypeError); -assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host') }, TypeError); -socket.close(); diff --git a/test/simple/test-dgram-send-bad-arguments.js b/test/simple/test-dgram-send-bad-arguments.js deleted file mode 100644 index a9a12d458..000000000 --- a/test/simple/test-dgram-send-bad-arguments.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dgram = require('dgram'); - -var buf = Buffer('test'); -var host = '127.0.0.1'; -var sock = dgram.createSocket('udp4'); - -assert.throws(function() { - sock.send(); -}, TypeError); // First argument should be a buffer. - -assert.throws(function() { sock.send(buf, -1, 1, 1, host); }, RangeError); -assert.throws(function() { sock.send(buf, 1, -1, 1, host); }, RangeError); -assert.throws(function() { sock.send(buf, 1, 1, -1, host); }, RangeError); -assert.throws(function() { sock.send(buf, 5, 1, 1, host); }, RangeError); -assert.throws(function() { sock.send(buf, 1, 5, 1, host); }, RangeError); -assert.throws(function() { sock.send(buf, 1, 1, 0, host); }, RangeError); -assert.throws(function() { sock.send(buf, 1, 1, 65536, host); }, RangeError); diff --git a/test/simple/test-dgram-send-callback-buffer-length.js b/test/simple/test-dgram-send-callback-buffer-length.js deleted file mode 100644 index c3b7d5ccc..000000000 --- a/test/simple/test-dgram-send-callback-buffer-length.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var dgram = require('dgram'); -var callbacks = 0; -var client, timer, buf, len, offset; - - -client = dgram.createSocket('udp4'); - -buf = new Buffer(256); -offset = 20; - -len = buf.length - offset; - - -client.send(buf, offset, len, common.PORT, "127.0.0.1", function (err, bytes) { - assert.notEqual(bytes, buf.length); - assert.equal(bytes, buf.length - offset); - clearTimeout(timer); - client.close(); -}); - -timer = setTimeout(function() { - throw new Error('Timeout'); -}, 200); diff --git a/test/simple/test-dgram-send-empty-buffer.js b/test/simple/test-dgram-send-empty-buffer.js deleted file mode 100644 index 4eb0ab4fc..000000000 --- a/test/simple/test-dgram-send-empty-buffer.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var dgram = require('dgram'); -var callbacks = 0; -var client, timer, buf; - -if (process.platform === 'darwin') { - console.error('Test is disabled due to 17894467 Apple bug'); - return; -} - - -client = dgram.createSocket('udp4'); - -client.bind(common.PORT); - -client.on('message', function (buffer, bytes) { - clearTimeout(timer); - client.close(); -}); - -buf = new Buffer(0); -client.send(buf, 0, 0, common.PORT, "127.0.0.1", function (err, len) { }); - -timer = setTimeout(function() { - throw new Error('Timeout'); -}, 200); diff --git a/test/simple/test-dgram-udp4.js b/test/simple/test-dgram-udp4.js deleted file mode 100644 index 838c48f2b..000000000 --- a/test/simple/test-dgram-udp4.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'), - dgram = require('dgram'), server, client, - server_port = 20989, - message_to_send = 'A message to send', - timer; - -server = dgram.createSocket('udp4'); -server.on('message', function(msg, rinfo) { - console.log('server got: ' + msg + - ' from ' + rinfo.address + ':' + rinfo.port); - assert.strictEqual(rinfo.address, '127.0.0.1'); - assert.strictEqual(msg.toString(), message_to_send.toString()); - server.send(msg, 0, msg.length, rinfo.port, rinfo.address); -}); -server.on('listening', function() { - var address = server.address(); - console.log('server is listening on ' + address.address + ':' + address.port); - client = dgram.createSocket('udp4'); - client.on('message', function(msg, rinfo) { - console.log('client got: ' + msg + - ' from ' + rinfo.address + ':' + address.port); - assert.strictEqual(rinfo.address, '127.0.0.1'); - assert.strictEqual(rinfo.port, server_port); - assert.strictEqual(msg.toString(), message_to_send.toString()); - client.close(); - server.close(); - }); - client.send(message_to_send, 0, message_to_send.length, - server_port, 'localhost', function(err) { - if (err) { - console.log('Caught error in client send.'); - throw err; - } - }); - client.on('close', - function() { - if (server.fd === null) { - clearTimeout(timer); - } - }); -}); -server.on('close', function() { - if (client.fd === null) { - clearTimeout(timer); - } -}); -server.bind(server_port); - -timer = setTimeout(function() { - throw new Error('Timeout'); -}, 200); diff --git a/test/simple/test-dgram-unref.js b/test/simple/test-dgram-unref.js deleted file mode 100644 index 38abbac27..000000000 --- a/test/simple/test-dgram-unref.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var dgram = require('dgram'); -var closed = false; - -var s = dgram.createSocket('udp4'); -s.bind(); -s.unref(); - -setTimeout(function() { - closed = true; - s.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); -}); diff --git a/test/simple/test-dh-padding.js b/test/simple/test-dh-padding.js deleted file mode 100644 index 753c0eb81..000000000 --- a/test/simple/test-dh-padding.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -var prime = 'c51f7bf8f0e1cf899243cdf408b1bc7c09c010e33ef7f3fbe5bd5feaf906113b'; -var apub = '6fe9f37037d8d017f908378c1ee04fe60e1cd3668bfc5075fac55c2f7153dd84'; -var bpub = '31d83e167fdf956c9dae6b980140577a9f8868acbfcbdc19113e58bfb9223abc'; -var apriv = '4fbfd4661f9181bbf574537b1a78adf473e8e771eef13c605e963c0f3094b697'; -var secret = '25616eed33f1af7975bbd0a8071d98a014f538b243bef90d76c08e81a0b3c500'; - -var p = crypto.createDiffieHellman(prime, 'hex'); - -p.setPublicKey(apub, 'hex'); -p.setPrivateKey(apriv, 'hex'); - -assert.equal( - p.computeSecret(bpub, 'hex', 'hex'), - '0025616eed33f1af7975bbd0a8071d98a014f538b243bef90d76c08e81a0b3c5' -); diff --git a/test/simple/test-dns-cares-domains.js b/test/simple/test-dns-cares-domains.js deleted file mode 100644 index 8581ed64d..000000000 --- a/test/simple/test-dns-cares-domains.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dns = require('dns'); -var domain = require('domain'); - -var methods = [ - 'resolve4', - 'resolve6', - 'resolveCname', - 'resolveMx', - 'resolveNs', - 'resolveTxt', - 'resolveSrv', - 'resolveNaptr', - 'resolveSoa' -] - -methods.forEach(function(method) { - var d = domain.create(); - d.run(function() { - dns[method]('google.com', function() { - assert.strictEqual(process.domain, d, method + ' retains domain') - }); - }); -}); diff --git a/test/simple/test-dns-lookup-cb-error.js b/test/simple/test-dns-lookup-cb-error.js deleted file mode 100644 index 036581098..000000000 --- a/test/simple/test-dns-lookup-cb-error.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cares = process.binding('cares_wrap'); - -var dns = require('dns'); - -// Stub `getaddrinfo` to *always* error. -cares.getaddrinfo = function() { - return process.binding('uv').UV_ENOENT; -}; - -assert.doesNotThrow(function() { - var tickValue = 0; - - dns.lookup('example.com', function(error, result, addressType) { - assert.equal(tickValue, 1); - assert.equal(error.code, 'ENOENT'); - }); - - // Make sure that the error callback is called - // on next tick. - tickValue = 1; -}); diff --git a/test/simple/test-dns-regress-6244.js b/test/simple/test-dns-regress-6244.js deleted file mode 100644 index ca2957926..000000000 --- a/test/simple/test-dns-regress-6244.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var dns = require('dns'); - -// Should not segfault, see #6244. -dns.resolve4('127.0.0.1', common.mustCall(function() { })); diff --git a/test/simple/test-dns-regress-7070.js b/test/simple/test-dns-regress-7070.js deleted file mode 100644 index 9aca4f728..000000000 --- a/test/simple/test-dns-regress-7070.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var dns = require('dns'); - -// Should not raise assertion error. Issue #7070 -assert.throws(function () { dns.resolveNs([]); }); // bad name -assert.throws(function () { dns.resolveNs(''); }); // bad callback diff --git a/test/simple/test-dns.js b/test/simple/test-dns.js deleted file mode 100644 index 405bcf0a0..000000000 --- a/test/simple/test-dns.js +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. - -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: - -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var dns = require('dns'); - -var existing = dns.getServers(); -assert(existing.length); - -function noop() {} - -var goog = [ - '8.8.8.8', - '8.8.4.4', -]; -assert.doesNotThrow(function () { dns.setServers(goog) }); -assert.deepEqual(dns.getServers(), goog); -assert.throws(function () { dns.setServers(['foobar']) }); -assert.deepEqual(dns.getServers(), goog); - -var goog6 = [ - '2001:4860:4860::8888', - '2001:4860:4860::8844', -]; -assert.doesNotThrow(function () { dns.setServers(goog6) }); -assert.deepEqual(dns.getServers(), goog6); - -goog6.push('4.4.4.4'); -dns.setServers(goog6); -assert.deepEqual(dns.getServers(), goog6); - -var ports = [ - '4.4.4.4:53', - '[2001:4860:4860::8888]:53', -]; -var portsExpected = [ - '4.4.4.4', - '2001:4860:4860::8888', -]; -dns.setServers(ports); -assert.deepEqual(dns.getServers(), portsExpected); - -assert.doesNotThrow(function () { dns.setServers([]); }); -assert.deepEqual(dns.getServers(), []); - -assert.throws(function() { - dns.resolve('test.com', [], noop); -}, function(err) { - return !(err instanceof TypeError); -}, 'Unexpected error'); - -// dns.lookup should accept falsey and string values -assert.throws(function() { - dns.lookup({}, noop); -}, 'invalid arguments: hostname must be a string or falsey'); - -assert.throws(function() { - dns.lookup([], noop); -}, 'invalid arguments: hostname must be a string or falsey'); - -assert.throws(function() { - dns.lookup(true, noop); -}, 'invalid arguments: hostname must be a string or falsey'); - -assert.throws(function() { - dns.lookup(1, noop); -}, 'invalid arguments: hostname must be a string or falsey'); - -assert.throws(function() { - dns.lookup(noop, noop); -}, 'invalid arguments: hostname must be a string or falsey'); - -assert.doesNotThrow(function() { - dns.lookup('', noop); -}); - -assert.doesNotThrow(function() { - dns.lookup(null, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup(undefined, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup(0, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup(NaN, noop); -}); - -/* - * Make sure that dns.lookup throws if hints does not represent a valid flag. - * (dns.V4MAPPED | dns.ADDRCONFIG) + 1 is invalid because: - * - it's different from dns.V4MAPPED and dns.ADDRCONFIG. - * - it's different from them bitwise ored. - * - it's different from 0. - * - it's an odd number different than 1, and thus is invalid, because - * flags are either === 1 or even. - */ -assert.throws(function() { - dns.lookup('www.google.com', { hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1 }, - noop); -}); - -assert.throws(function() { - dns.lookup('www.google.com'); -}, 'invalid arguments: callback must be passed'); - -assert.throws(function() { - dns.lookup('www.google.com', 4); -}, 'invalid arguments: callback must be passed'); - -assert.doesNotThrow(function() { - dns.lookup('www.google.com', 6, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup('www.google.com', {}, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup('www.google.com', { - family: 4, - hints: 0 - }, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup('www.google.com', { - family: 6, - hints: dns.ADDRCONFIG - }, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup('www.google.com', { - hints: dns.V4MAPPED - }, noop); -}); - -assert.doesNotThrow(function() { - dns.lookup('www.google.com', { - hints: dns.ADDRCONFIG | dns.V4MAPPED - }, noop); -}); diff --git a/test/simple/test-domain-crypto.js b/test/simple/test-domain-crypto.js deleted file mode 100644 index 66e962880..000000000 --- a/test/simple/test-domain-crypto.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -try { - var crypto = require('crypto'); -} catch (e) { - console.log('Not compiled with OPENSSL support.'); - process.exit(); -} - -// the missing var keyword is intentional -domain = require('domain'); - -// should not throw a 'TypeError: undefined is not a function' exception -crypto.randomBytes(8); -crypto.randomBytes(8, function() {}); -crypto.pseudoRandomBytes(8); -crypto.pseudoRandomBytes(8, function() {}); -crypto.pbkdf2('password', 'salt', 8, 8, function() {}); diff --git a/test/simple/test-domain-enter-exit.js b/test/simple/test-domain-enter-exit.js deleted file mode 100644 index 7d248ea15..000000000 --- a/test/simple/test-domain-enter-exit.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Make sure the domain stack is a stack - -var assert = require('assert'); -var domain = require('domain'); - -function names(array) { - return array.map(function(d) { - return d.name - }).join(', '); -} - -var a = domain.create(); -a.name = 'a'; -var b = domain.create(); -b.name = 'b'; -var c = domain.create(); -c.name = 'c'; - -a.enter(); // push -assert.deepEqual(domain._stack, [a], - 'a not pushed: ' + names(domain._stack)); - -b.enter(); // push -assert.deepEqual(domain._stack, [a, b], - 'b not pushed: ' + names(domain._stack)); - -c.enter(); // push -assert.deepEqual(domain._stack, [a, b, c], - 'c not pushed: ' + names(domain._stack)); - -b.exit(); // pop -assert.deepEqual(domain._stack, [a], - 'b and c not popped: ' + names(domain._stack)); - -b.enter(); // push -assert.deepEqual(domain._stack, [a, b], - 'b not pushed: ' + names(domain._stack)); diff --git a/test/simple/test-domain-exit-dispose-again.js b/test/simple/test-domain-exit-dispose-again.js deleted file mode 100644 index 22928f260..000000000 --- a/test/simple/test-domain-exit-dispose-again.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var domain = require('domain'); -var disposalFailed = false; - -// no matter what happens, we should increment a 10 times. -var a = 0; -log(); -function log(){ - console.log(a++, process.domain); - if (a < 10) setTimeout(log, 20); -} - -var secondTimerRan = false; - -// in 50ms we'll throw an error. -setTimeout(err, 50); -setTimeout(secondTimer, 50); -function err(){ - var d = domain.create(); - d.on('error', handle); - d.run(err2); - - function err2() { - // this timeout should never be called, since the domain gets - // disposed when the error happens. - setTimeout(function() { - console.error('This should not happen.'); - disposalFailed = true; - process.exit(1); - }); - - // this function doesn't exist, and throws an error as a result. - err3(); - } - - function handle(e) { - // this should clean up everything properly. - d.dispose(); - console.error(e); - console.error('in handler', process.domain, process.domain === d); - } -} - -function secondTimer() { - console.log('In second timer'); - secondTimerRan = true; -} - -process.on('exit', function() { - assert.equal(a, 10); - assert.equal(disposalFailed, false); - assert(secondTimerRan); - console.log('ok'); -}); diff --git a/test/simple/test-domain-exit-dispose.js b/test/simple/test-domain-exit-dispose.js deleted file mode 100644 index fd990911c..000000000 --- a/test/simple/test-domain-exit-dispose.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var domain = require('domain'); -var disposalFailed = false; - -// no matter what happens, we should increment a 10 times. -var a = 0; -log(); -function log(){ - console.log(a++, process.domain); - if (a < 10) setTimeout(log, 20); -} - -// in 50ms we'll throw an error. -setTimeout(err, 50); -function err(){ - var d = domain.create(); - d.on('error', handle); - d.run(err2); - - function err2() { - // this timeout should never be called, since the domain gets - // disposed when the error happens. - setTimeout(function() { - console.error('This should not happen.'); - disposalFailed = true; - process.exit(1); - }); - - // this function doesn't exist, and throws an error as a result. - err3(); - } - - function handle(e) { - // this should clean up everything properly. - d.dispose(); - console.error(e); - console.error('in handler', process.domain, process.domain === d); - } -} - -process.on('exit', function() { - assert.equal(a, 10); - assert.equal(disposalFailed, false); - console.log('ok'); -}); diff --git a/test/simple/test-domain-from-timer.js b/test/simple/test-domain-from-timer.js deleted file mode 100644 index 3e73a5c4b..000000000 --- a/test/simple/test-domain-from-timer.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Simple tests of most basic domain functionality. - -var common = require('../common'); -var assert = require('assert'); - -// timeouts call the callback directly from cc, so need to make sure the -// domain will be used regardless -setTimeout(function() { - var domain = require('domain'); - var d = domain.create(); - d.run(function() { - process.nextTick(function() { - console.trace('in nexttick', process.domain === d) - assert.equal(process.domain, d); - }); - }); -}); diff --git a/test/simple/test-domain-http-server.js b/test/simple/test-domain-http-server.js deleted file mode 100644 index 57e8ac4d1..000000000 --- a/test/simple/test-domain-http-server.js +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var domain = require('domain'); -var http = require('http'); -var assert = require('assert'); -var common = require('../common.js'); - -var objects = { foo: 'bar', baz: {}, num: 42, arr: [1,2,3] }; -objects.baz.asdf = objects; - -var serverCaught = 0; -var clientCaught = 0; -var disposeEmit = 0; - -var server = http.createServer(function(req, res) { - var dom = domain.create(); - req.resume(); - dom.add(req); - dom.add(res); - - dom.on('error', function(er) { - serverCaught++; - console.log('horray! got a server error', er); - // try to send a 500. If that fails, oh well. - res.writeHead(500, {'content-type':'text/plain'}); - res.end(er.stack || er.message || 'Unknown error'); - }); - - dom.run(function() { - // Now, an action that has the potential to fail! - // if you request 'baz', then it'll throw a JSON circular ref error. - var data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); - - // this line will throw if you pick an unknown key - assert(data !== undefined, 'Data should not be undefined'); - - res.writeHead(200); - res.end(data); - }); -}); - -server.listen(common.PORT, next); - -function next() { - console.log('listening on localhost:%d', common.PORT); - - var requests = 0; - var responses = 0; - - makeReq('/'); - makeReq('/foo'); - makeReq('/arr'); - makeReq('/baz'); - makeReq('/num'); - - function makeReq(p) { - requests++; - - var dom = domain.create(); - dom.on('error', function(er) { - clientCaught++; - console.log('client error', er); - req.socket.destroy(); - }); - - var req = http.get({ host: 'localhost', port: common.PORT, path: p }); - dom.add(req); - req.on('response', function(res) { - responses++; - console.error('requests=%d responses=%d', requests, responses); - if (responses === requests) { - console.error('done, closing server'); - // no more coming. - server.close(); - } - - dom.add(res); - var d = ''; - res.on('data', function(c) { - d += c; - }); - res.on('end', function() { - console.error('trying to parse json', d); - d = JSON.parse(d); - console.log('json!', d); - }); - }); - } -} - -process.on('exit', function() { - assert.equal(serverCaught, 2); - assert.equal(clientCaught, 2); - console.log('ok'); -}); diff --git a/test/simple/test-domain-implicit-fs.js b/test/simple/test-domain-implicit-fs.js deleted file mode 100644 index c701c9315..000000000 --- a/test/simple/test-domain-implicit-fs.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Simple tests of most basic domain functionality. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); -var events = require('events'); -var caught = 0; -var expectCaught = 1; - -var d = new domain.Domain(); -var e = new events.EventEmitter(); - -d.on('error', function(er) { - console.error('caught', er); - - assert.strictEqual(er.domain, d); - assert.strictEqual(er.domainThrown, true); - assert.ok(!er.domainEmitter); - assert.strictEqual(er.code, 'ENOENT'); - assert.ok(/\bthis file does not exist\b/i.test(er.path)); - assert.strictEqual(typeof er.errno, 'number'); - - caught++; -}); - -process.on('exit', function() { - console.error('exit'); - assert.equal(caught, expectCaught); - console.log('ok'); -}); - - -// implicit handling of thrown errors while in a domain, via the -// single entry points of ReqWrap and MakeCallback. Even if -// we try very hard to escape, there should be no way to, even if -// we go many levels deep through timeouts and multiple IO calls. -// Everything that happens between the domain.enter() and domain.exit() -// calls will be bound to the domain, even if multiple levels of -// handles are created. -d.run(function() { - setTimeout(function() { - var fs = require('fs'); - fs.readdir(__dirname, function() { - fs.open('this file does not exist', 'r', function(er) { - if (er) throw er; - throw new Error('should not get here!'); - }); - }); - }, 100); -}); diff --git a/test/simple/test-domain-multi.js b/test/simple/test-domain-multi.js deleted file mode 100644 index 68e4b11a6..000000000 --- a/test/simple/test-domain-multi.js +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Tests of multiple domains happening at once. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); -var events = require('events'); - -var caughtA = false; -var caughtB = false; -var caughtC = false; - - -var a = domain.create(); -a.enter(); // this will be our "root" domain -a.on('error', function(er) { - caughtA = true; - console.log('This should not happen'); - throw er; -}); - - -var http = require('http'); -var server = http.createServer(function (req, res) { - // child domain of a. - var b = domain.create(); - a.add(b); - - // treat these EE objects as if they are a part of the b domain - // so, an 'error' event on them propagates to the domain, rather - // than being thrown. - b.add(req); - b.add(res); - - b.on('error', function (er) { - caughtB = true; - console.error('Error encountered', er) - if (res) { - res.writeHead(500); - res.end('An error occurred'); - } - // res.writeHead(500), res.destroy, etc. - server.close(); - }); - - // XXX this bind should not be necessary. - // the write cb behavior in http/net should use an - // event so that it picks up the domain handling. - res.write('HELLO\n', b.bind(function() { - throw new Error('this kills domain B, not A'); - })); - -}).listen(common.PORT); - -var c = domain.create(); -var req = http.get({ host: 'localhost', port: common.PORT }) - -// add the request to the C domain -c.add(req); - -req.on('response', function(res) { - console.error('got response'); - // add the response object to the C domain - c.add(res); - res.pipe(process.stdout); -}); - -c.on('error', function(er) { - caughtC = true; - console.error('Error on c', er.message); -}); - -process.on('exit', function() { - assert.equal(caughtA, false); - assert.equal(caughtB, true) - assert.equal(caughtC, true) - console.log('ok - Errors went where they were supposed to go'); -}); diff --git a/test/simple/test-domain-nested-throw.js b/test/simple/test-domain-nested-throw.js deleted file mode 100644 index e11948667..000000000 --- a/test/simple/test-domain-nested-throw.js +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var domain = require('domain'); - -var dispose; -switch (process.argv[2]) { - case 'true': - dispose = true; - break; - case 'false': - dispose = false; - break; - default: - parent(); - return; -} - -function parent() { - var node = process.execPath; - var spawn = require('child_process').spawn; - var opt = { stdio: 'inherit' }; - var child = spawn(node, [__filename, 'true'], opt); - child.on('exit', function(c) { - assert(!c); - child = spawn(node, [__filename, 'false'], opt); - child.on('exit', function(c) { - assert(!c); - console.log('ok'); - }); - }); -} - -var gotDomain1Error = false; -var gotDomain2Error = false; - -var threw1 = false; -var threw2 = false; - -function throw1() { - threw1 = true; - throw new Error('handled by domain1'); -} - -function throw2() { - threw2 = true; - throw new Error('handled by domain2'); -} - -function inner(throw1, throw2) { - var domain1 = domain.createDomain(); - - domain1.on('error', function (err) { - if (gotDomain1Error) { - console.error('got domain 1 twice'); - process.exit(1); - } - if (dispose) domain1.dispose(); - gotDomain1Error = true; - throw2(); - }); - - domain1.run(function () { - throw1(); - }); -} - -function outer() { - var domain2 = domain.createDomain(); - - domain2.on('error', function (err) { - if (gotDomain2Error) { - console.error('got domain 2 twice'); - process.exit(1); - } - gotDomain2Error = true; - }); - - domain2.run(function () { - inner(throw1, throw2); - }); -} - -process.on('exit', function() { - assert(gotDomain1Error); - assert(gotDomain2Error); - assert(threw1); - assert(threw2); - console.log('ok', dispose); -}); - -outer(); diff --git a/test/simple/test-domain-nested.js b/test/simple/test-domain-nested.js deleted file mode 100644 index efd672b25..000000000 --- a/test/simple/test-domain-nested.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Make sure that the nested domains don't cause the domain stack to grow - -var assert = require('assert'); -var domain = require('domain'); - -process.on('exit', function(c) { - assert.equal(domain._stack.length, 0); -}); - -domain.create().run(function() { - domain.create().run(function() { - domain.create().run(function() { - domain.create().on("error", function(e) { - // Don't need to do anything here - }).run(function() { - throw new Error("died") - }) - }) - }) -}) diff --git a/test/simple/test-domain-safe-exit.js b/test/simple/test-domain-safe-exit.js deleted file mode 100644 index a7dcef078..000000000 --- a/test/simple/test-domain-safe-exit.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Make sure the domain stack doesn't get clobbered by un-matched .exit() - -var assert = require('assert'); -var domain = require('domain'); - -var a = domain.create(); -var b = domain.create(); - -a.enter(); // push -b.enter(); // push -assert.deepEqual(domain._stack, [a, b], 'b not pushed'); - -domain.create().exit(); // no-op -assert.deepEqual(domain._stack, [a, b], 'stack mangled!'); diff --git a/test/simple/test-domain-stack.js b/test/simple/test-domain-stack.js deleted file mode 100644 index eecb85b4b..000000000 --- a/test/simple/test-domain-stack.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Make sure that the domain stack doesn't get out of hand. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); -var events = require('events'); - -var a = domain.create(); -a.name = 'a'; - -a.on('error', function() { - if (domain._stack.length > 5) { - console.error('leaking!', domain._stack); - process.exit(1); - } -}); - -var foo = a.bind(function() { - throw new Error('error from foo'); -}); - -for (var i = 0; i < 1000; i++) { - process.nextTick(foo); -} - -process.on('exit', function(c) { - if (!c) console.log('ok'); -}); diff --git a/test/simple/test-domain-timers.js b/test/simple/test-domain-timers.js deleted file mode 100644 index 388673c08..000000000 --- a/test/simple/test-domain-timers.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var domain = require('domain'); -var assert = require('assert'); -var common = require('../common.js'); - -var timeout_err, timeout, immediate_err; - -var timeoutd = domain.create(); - -timeoutd.on('error', function(e) { - timeout_err = e; - clearTimeout(timeout); -}); - -timeoutd.run(function() { - setTimeout(function() { - throw new Error('Timeout UNREFd'); - }).unref(); -}); - -var immediated = domain.create(); - -immediated.on('error', function(e) { - immediate_err = e; -}); - -immediated.run(function() { - setImmediate(function() { - throw new Error('Immediate Error'); - }); -}); - -timeout = setTimeout(function() {}, 10 * 1000); - -process.on('exit', function() { - assert.equal(timeout_err.message, 'Timeout UNREFd', - 'Domain should catch timer error'); - assert.equal(immediate_err.message, 'Immediate Error', - 'Domain should catch immediate error'); -}); diff --git a/test/simple/test-domain.js b/test/simple/test-domain.js deleted file mode 100644 index 41eb602e4..000000000 --- a/test/simple/test-domain.js +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// Simple tests of most basic domain functionality. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); -var events = require('events'); -var fs = require('fs'); -var caught = 0; -var expectCaught = 0; - -var d = new domain.Domain(); -var e = new events.EventEmitter(); - -d.on('error', function(er) { - console.error('caught', er && (er.message || er)); - - var er_message = er.message; - var er_path = er.path - - // On windows, error messages can contain full path names. If this is the - // case, remove the directory part. - if (typeof er_path === 'string') { - var slash = er_path.lastIndexOf('\\'); - if (slash !== -1) { - var dir = er_path.slice(0, slash + 1); - er_path = er_path.replace(dir, ''); - er_message = er_message.replace(dir, ''); - } - } - - switch (er_message) { - case 'emitted': - assert.equal(er.domain, d); - assert.equal(er.domainEmitter, e); - assert.equal(er.domainThrown, false); - break; - - case 'bound': - assert.ok(!er.domainEmitter); - assert.equal(er.domain, d); - assert.equal(er.domainBound, fn); - assert.equal(er.domainThrown, false); - break; - - case 'thrown': - assert.ok(!er.domainEmitter); - assert.equal(er.domain, d); - assert.equal(er.domainThrown, true); - break; - - case "ENOENT, open 'this file does not exist'": - assert.equal(er.domain, d); - assert.equal(er.domainThrown, false); - assert.equal(typeof er.domainBound, 'function'); - assert.ok(!er.domainEmitter); - assert.equal(er.code, 'ENOENT'); - assert.equal(er_path, 'this file does not exist'); - assert.equal(typeof er.errno, 'number'); - break; - - case "ENOENT, open 'stream for nonexistent file'": - assert.equal(typeof er.errno, 'number'); - assert.equal(er.code, 'ENOENT'); - assert.equal(er_path, 'stream for nonexistent file'); - assert.equal(er.domain, d); - assert.equal(er.domainEmitter, fst); - assert.ok(!er.domainBound); - assert.equal(er.domainThrown, false); - break; - - case 'implicit': - assert.equal(er.domainEmitter, implicit); - assert.equal(er.domain, d); - assert.equal(er.domainThrown, false); - assert.ok(!er.domainBound); - break; - - case 'implicit timer': - assert.equal(er.domain, d); - assert.equal(er.domainThrown, true); - assert.ok(!er.domainEmitter); - assert.ok(!er.domainBound); - break; - - case 'Cannot read property \'isDirectory\' of undefined': - assert.equal(er.domain, d); - assert.ok(!er.domainEmitter); - assert.ok(!er.domainBound); - break; - - case 'nextTick execution loop': - assert.equal(er.domain, d); - assert.ok(!er.domainEmitter); - assert.ok(!er.domainBound); - break; - - default: - console.error('unexpected error, throwing %j', er.message, er); - throw er; - } - - caught++; -}); - - - -process.on('exit', function() { - console.error('exit', caught, expectCaught); - assert.equal(caught, expectCaught, 'caught the expected number of errors'); - console.log('ok'); -}); - - - -// revert to using the domain when a callback is passed to nextTick in -// the middle of a tickCallback loop -d.run(function() { - process.nextTick(function() { - throw new Error('nextTick execution loop'); - }); -}); -expectCaught++; - - - -// catch thrown errors no matter how many times we enter the event loop -// this only uses implicit binding, except for the first function -// passed to d.run(). The rest are implicitly bound by virtue of being -// set up while in the scope of the d domain. -d.run(function() { - process.nextTick(function() { - var i = setInterval(function () { - clearInterval(i); - setTimeout(function() { - fs.stat('this file does not exist', function(er, stat) { - // uh oh! stat isn't set! - // pretty common error. - console.log(stat.isDirectory()); - }); - }); - }); - }); -}); -expectCaught++; - - - -// implicit addition of a timer created within a domain-bound context. -d.run(function() { - setTimeout(function() { - throw new Error('implicit timer'); - }); -}); -expectCaught++; - - - -// Event emitters added to the domain have their errors routed. -d.add(e); -e.emit('error', new Error('emitted')); -expectCaught++; - - - -// get rid of the `if (er) return cb(er)` malarky, by intercepting -// the cb functions to the domain, and using the intercepted function -// as a callback instead. -function fn(er) { - throw new Error('This function should never be called!'); - process.exit(1); -} - -var bound = d.intercept(fn); -bound(new Error('bound')); -expectCaught++; - - - -// intercepted should never pass first argument to callback -function fn2(data) { - assert.equal(data, 'data', 'should not be null err argument') -} - -var bound = d.intercept(fn2); -bound(null, 'data'); - -// intercepted should never pass first argument to callback -// even if arguments length is more than 2. -function fn3(data, data2) { - assert.equal(data, 'data', 'should not be null err argument'); - assert.equal(data2, 'data2', 'should not be data argument'); -} - -bound = d.intercept(fn3); -bound(null, 'data', 'data2'); - -// throwing in a bound fn is also caught, -// even if it's asynchronous, by hitting the -// global uncaughtException handler. This doesn't -// require interception, since throws are always -// caught by the domain. -function thrower() { - throw new Error('thrown'); -} -setTimeout(d.bind(thrower), 100); -expectCaught++; - - - -// Pass an intercepted function to an fs operation that fails. -fs.open('this file does not exist', 'r', d.intercept(function(er) { - console.error('should not get here!', er); - throw new Error('should not get here!'); -}, true)); -expectCaught++; - - - -// implicit addition by being created within a domain-bound context. -var implicit; - -d.run(function() { - implicit = new events.EventEmitter; -}); - -setTimeout(function() { - // escape from the domain, but implicit is still bound to it. - implicit.emit('error', new Error('implicit')); -}, 10); -expectCaught++; - - -var result = d.run(function () { - return 'return value'; -}); -assert.equal(result, 'return value'); - - -// check if the executed function take in count the applied parameters -result = d.run(function (a, b) { - return a + ' ' + b; -}, 'return', 'value'); -assert.equal(result, 'return value'); - - -var fst = fs.createReadStream('stream for nonexistent file') -d.add(fst) -expectCaught++; - -[42, null, , false, function(){}, 'string'].forEach(function(something) { - var d = new domain.Domain(); - d.run(function() { - process.nextTick(function() { - throw something; - }); - expectCaught++; - }); - - d.on('error', function(er) { - assert.strictEqual(something, er); - caught++; - }); -}); diff --git a/test/simple/test-error-reporting.js b/test/simple/test-error-reporting.js deleted file mode 100644 index c187998dd..000000000 --- a/test/simple/test-error-reporting.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; -var path = require('path'); - -var exits = 0; - -function errExec(script, callback) { - var cmd = '"' + process.argv[0] + '" "' + - path.join(common.fixturesDir, script) + '"'; - return exec(cmd, function(err, stdout, stderr) { - // There was some error - assert.ok(err); - - // More than one line of error output. - assert.ok(stderr.split('\n').length > 2); - - // Assert the script is mentioned in error output. - assert.ok(stderr.indexOf(script) >= 0); - - // Proxy the args for more tests. - callback(err, stdout, stderr); - - // Count the tests - exits++; - - console.log('.'); - }); -} - - -// Simple throw error -errExec('throws_error.js', function(err, stdout, stderr) { - assert.ok(/blah/.test(stderr)); -}); - - -// Trying to JSON.parse(undefined) -errExec('throws_error2.js', function(err, stdout, stderr) { - assert.ok(/SyntaxError/.test(stderr)); -}); - - -// Trying to JSON.parse(undefined) in nextTick -errExec('throws_error3.js', function(err, stdout, stderr) { - assert.ok(/SyntaxError/.test(stderr)); -}); - - -// throw ILLEGAL error -errExec('throws_error4.js', function(err, stdout, stderr) { - assert.ok(/\/\*\*/.test(stderr)); - assert.ok(/SyntaxError/.test(stderr)); -}); - - -process.on('exit', function() { - assert.equal(4, exits); -}); diff --git a/test/simple/test-eval-require.js b/test/simple/test-eval-require.js deleted file mode 100644 index dfef416ce..000000000 --- a/test/simple/test-eval-require.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var path = require('path'); -var fs = require('fs'); - -var options = { - cwd: common.fixturesDir -}; -var child = spawn(process.execPath, ['-e', 'require("foo")'], options); -child.on('exit', function(code) { - assert.equal(code, 0); -}); - diff --git a/test/simple/test-eval.js b/test/simple/test-eval.js deleted file mode 100644 index 9c656a877..000000000 --- a/test/simple/test-eval.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -require('../common'); -var util = require('util'); -var assert = require('assert'); -var exec = require('child_process').exec; - -var success_count = 0; -var error_count = 0; - -var cmd = [process.execPath, '-e', '"console.error(process.argv)"', - 'foo', 'bar'].join(' '); -var expected = util.format([process.execPath, 'foo', 'bar']) + '\n'; -var child = exec(cmd, function(err, stdout, stderr) { - if (err) { - console.log(err.toString()); - ++error_count; - return; - } - assert.equal(stderr, expected); - ++success_count; -}); - -process.on('exit', function() { - assert.equal(1, success_count); - assert.equal(0, error_count); -}); - diff --git a/test/simple/test-event-emitter-add-listeners.js b/test/simple/test-event-emitter-add-listeners.js deleted file mode 100644 index 0806e049d..000000000 --- a/test/simple/test-event-emitter-add-listeners.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var e = new events.EventEmitter(); - -var events_new_listener_emited = []; -var listeners_new_listener_emited = []; -var times_hello_emited = 0; - -// sanity check -assert.equal(e.addListener, e.on); - -e.on('newListener', function(event, listener) { - console.log('newListener: ' + event); - events_new_listener_emited.push(event); - listeners_new_listener_emited.push(listener); -}); - -function hello(a, b) { - console.log('hello'); - times_hello_emited += 1; - assert.equal('a', a); - assert.equal('b', b); -} -e.on('hello', hello); - -var foo = function() {}; -e.once('foo', foo); - -console.log('start'); - -e.emit('hello', 'a', 'b'); - - -// just make sure that this doesn't throw: -var f = new events.EventEmitter(); -f.setMaxListeners(0); - - -process.on('exit', function() { - assert.deepEqual(['hello', 'foo'], events_new_listener_emited); - assert.deepEqual([hello, foo], listeners_new_listener_emited); - assert.equal(1, times_hello_emited); -}); - - diff --git a/test/simple/test-event-emitter-check-listener-leaks.js b/test/simple/test-event-emitter-check-listener-leaks.js deleted file mode 100644 index d073e5de1..000000000 --- a/test/simple/test-event-emitter-check-listener-leaks.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var e = new events.EventEmitter(); - -// default -for (var i = 0; i < 10; i++) { - e.on('default', function() {}); -} -assert.ok(!e._events['default'].hasOwnProperty('warned')); -e.on('default', function() {}); -assert.ok(e._events['default'].warned); - -// specific -e.setMaxListeners(5); -for (var i = 0; i < 5; i++) { - e.on('specific', function() {}); -} -assert.ok(!e._events['specific'].hasOwnProperty('warned')); -e.on('specific', function() {}); -assert.ok(e._events['specific'].warned); - -// only one -e.setMaxListeners(1); -e.on('only one', function() {}); -assert.ok(!e._events['only one'].hasOwnProperty('warned')); -e.on('only one', function() {}); -assert.ok(e._events['only one'].hasOwnProperty('warned')); - -// unlimited -e.setMaxListeners(0); -for (var i = 0; i < 1000; i++) { - e.on('unlimited', function() {}); -} -assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); - -// process-wide -events.EventEmitter.defaultMaxListeners = 42; -e = new events.EventEmitter(); - -for (var i = 0; i < 42; ++i) { - e.on('fortytwo', function() {}); -} -assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); -e.on('fortytwo', function() {}); -assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); -delete e._events['fortytwo'].warned; - -events.EventEmitter.defaultMaxListeners = 44; -e.on('fortytwo', function() {}); -assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); -e.on('fortytwo', function() {}); -assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); - -// but _maxListeners still has precedence over defaultMaxListeners -events.EventEmitter.defaultMaxListeners = 42; -e = new events.EventEmitter(); -e.setMaxListeners(1); -e.on('uno', function() {}); -assert.ok(!e._events['uno'].hasOwnProperty('warned')); -e.on('uno', function() {}); -assert.ok(e._events['uno'].hasOwnProperty('warned')); - -// chainable -assert.strictEqual(e, e.setMaxListeners(1)); diff --git a/test/simple/test-event-emitter-get-max-listeners.js b/test/simple/test-event-emitter-get-max-listeners.js deleted file mode 100644 index 8e47ef7a7..000000000 --- a/test/simple/test-event-emitter-get-max-listeners.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright io.js contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var EventEmitter = require('events'); - -var emitter = new EventEmitter(); - -assert.strictEqual(emitter.getMaxListeners(), EventEmitter.defaultMaxListeners); - -emitter.setMaxListeners(0) -assert.strictEqual(emitter.getMaxListeners(), 0) - -emitter.setMaxListeners(3) -assert.strictEqual(emitter.getMaxListeners(), 3) diff --git a/test/simple/test-event-emitter-listeners-side-effects.js b/test/simple/test-event-emitter-listeners-side-effects.js deleted file mode 100644 index c6218e059..000000000 --- a/test/simple/test-event-emitter-listeners-side-effects.js +++ /dev/null @@ -1,61 +0,0 @@ - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var EventEmitter = require('events').EventEmitter; -var assert = require('assert'); - -var e = new EventEmitter; -var fl; // foo listeners - -fl = e.listeners('foo'); -assert(Array.isArray(fl)); -assert(fl.length === 0); -assert.deepEqual(e._events, {}); - -e.on('foo', assert.fail); -fl = e.listeners('foo'); -assert(e._events.foo === assert.fail); -assert(Array.isArray(fl)); -assert(fl.length === 1); -assert(fl[0] === assert.fail); - -e.listeners('bar'); -assert(!e._events.hasOwnProperty('bar')); - -e.on('foo', assert.ok); -fl = e.listeners('foo'); - -assert(Array.isArray(e._events.foo)); -assert(e._events.foo.length === 2); -assert(e._events.foo[0] === assert.fail); -assert(e._events.foo[1] === assert.ok); - -assert(Array.isArray(fl)); -assert(fl.length === 2); -assert(fl[0] === assert.fail); -assert(fl[1] === assert.ok); - -console.log('ok'); diff --git a/test/simple/test-event-emitter-listeners.js b/test/simple/test-event-emitter-listeners.js deleted file mode 100644 index 3e622835b..000000000 --- a/test/simple/test-event-emitter-listeners.js +++ /dev/null @@ -1,52 +0,0 @@ - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -function listener() {} -function listener2() {} - -var e1 = new events.EventEmitter(); -e1.on('foo', listener); -var fooListeners = e1.listeners('foo'); -assert.deepEqual(e1.listeners('foo'), [listener]); -e1.removeAllListeners('foo'); -assert.deepEqual(e1.listeners('foo'), []); -assert.deepEqual(fooListeners, [listener]); - -var e2 = new events.EventEmitter(); -e2.on('foo', listener); -var e2ListenersCopy = e2.listeners('foo'); -assert.deepEqual(e2ListenersCopy, [listener]); -assert.deepEqual(e2.listeners('foo'), [listener]); -e2ListenersCopy.push(listener2); -assert.deepEqual(e2.listeners('foo'), [listener]); -assert.deepEqual(e2ListenersCopy, [listener, listener2]); - -var e3 = new events.EventEmitter(); -e3.on('foo', listener); -var e3ListenersCopy = e3.listeners('foo'); -e3.on('foo', listener2); -assert.deepEqual(e3.listeners('foo'), [listener, listener2]); -assert.deepEqual(e3ListenersCopy, [listener]); diff --git a/test/simple/test-event-emitter-max-listeners.js b/test/simple/test-event-emitter-max-listeners.js deleted file mode 100644 index dfc3e1352..000000000 --- a/test/simple/test-event-emitter-max-listeners.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var gotEvent = false; - -process.on('exit', function() { - assert(gotEvent); -}); - -var e = new events.EventEmitter(); - -e.on('maxListeners', function() { - gotEvent = true; -}); - -// Should not corrupt the 'maxListeners' queue. -e.setMaxListeners(42); - -assert.throws(function() { - e.setMaxListeners(NaN); -}); - -assert.throws(function() { - e.setMaxListeners(-1); -}); - -assert.throws(function() { - e.setMaxListeners("and even this"); -}); - -e.emit('maxListeners'); diff --git a/test/simple/test-event-emitter-method-names.js b/test/simple/test-event-emitter-method-names.js deleted file mode 100644 index 60d16b397..000000000 --- a/test/simple/test-event-emitter-method-names.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var E = events.EventEmitter.prototype; -assert.equal(E.constructor.name, 'EventEmitter'); -assert.equal(E.on, E.addListener); // Same method. -Object.getOwnPropertyNames(E).forEach(function(name) { - if (name === 'constructor' || name === 'on') return; - if (typeof E[name] !== 'function') return; - assert.equal(E[name].name, name); -}); diff --git a/test/simple/test-event-emitter-modify-in-emit.js b/test/simple/test-event-emitter-modify-in-emit.js deleted file mode 100644 index 738af098c..000000000 --- a/test/simple/test-event-emitter-modify-in-emit.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var callbacks_called = []; - -var e = new events.EventEmitter(); - -function callback1() { - callbacks_called.push('callback1'); - e.on('foo', callback2); - e.on('foo', callback3); - e.removeListener('foo', callback1); -} - -function callback2() { - callbacks_called.push('callback2'); - e.removeListener('foo', callback2); -} - -function callback3() { - callbacks_called.push('callback3'); - e.removeListener('foo', callback3); -} - -e.on('foo', callback1); -assert.equal(1, e.listeners('foo').length); - -e.emit('foo'); -assert.equal(2, e.listeners('foo').length); -assert.deepEqual(['callback1'], callbacks_called); - -e.emit('foo'); -assert.equal(0, e.listeners('foo').length); -assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); - -e.emit('foo'); -assert.equal(0, e.listeners('foo').length); -assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called); - -e.on('foo', callback1); -e.on('foo', callback2); -assert.equal(2, e.listeners('foo').length); -e.removeAllListeners('foo'); -assert.equal(0, e.listeners('foo').length); - -// Verify that removing callbacks while in emit allows emits to propagate to -// all listeners -callbacks_called = []; - -e.on('foo', callback2); -e.on('foo', callback3); -assert.equal(2, e.listeners('foo').length); -e.emit('foo'); -assert.deepEqual(['callback2', 'callback3'], callbacks_called); -assert.equal(0, e.listeners('foo').length); diff --git a/test/simple/test-event-emitter-no-error-provided-to-error-event.js b/test/simple/test-event-emitter-no-error-provided-to-error-event.js deleted file mode 100644 index 79f14904e..000000000 --- a/test/simple/test-event-emitter-no-error-provided-to-error-event.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); -var domain = require('domain'); - -var errorCatched = false; - -var e = new events.EventEmitter(); - -var d = domain.create(); -d.add(e); -d.on('error', function (er) { - assert(er instanceof Error, 'error created'); - errorCatched = true; -}); - -e.emit('error'); - -process.on('exit', function () { - assert(errorCatched, 'error got caught'); -}); diff --git a/test/simple/test-event-emitter-num-args.js b/test/simple/test-event-emitter-num-args.js deleted file mode 100644 index 037c56965..000000000 --- a/test/simple/test-event-emitter-num-args.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var e = new events.EventEmitter(), - num_args_emited = []; - -e.on('numArgs', function() { - var numArgs = arguments.length; - console.log('numArgs: ' + numArgs); - num_args_emited.push(numArgs); -}); - -console.log('start'); - -e.emit('numArgs'); -e.emit('numArgs', null); -e.emit('numArgs', null, null); -e.emit('numArgs', null, null, null); -e.emit('numArgs', null, null, null, null); -e.emit('numArgs', null, null, null, null, null); - -process.on('exit', function() { - assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited); -}); - - diff --git a/test/simple/test-event-emitter-once.js b/test/simple/test-event-emitter-once.js deleted file mode 100644 index 2eaebcc7a..000000000 --- a/test/simple/test-event-emitter-once.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var e = new events.EventEmitter(); -var times_hello_emited = 0; - -e.once('hello', function(a, b) { - times_hello_emited++; -}); - -e.emit('hello', 'a', 'b'); -e.emit('hello', 'a', 'b'); -e.emit('hello', 'a', 'b'); -e.emit('hello', 'a', 'b'); - -var remove = function() { - assert.fail(1, 0, 'once->foo should not be emitted', '!'); -}; - -e.once('foo', remove); -e.removeListener('foo', remove); -e.emit('foo'); - -process.on('exit', function() { - assert.equal(1, times_hello_emited); -}); - -var times_recurse_emitted = 0; - -e.once('e', function() { - e.emit('e'); - times_recurse_emitted++; -}); - -e.once('e', function() { - times_recurse_emitted++; -}); - -e.emit('e'); - -process.on('exit', function() { - assert.equal(2, times_recurse_emitted); -}); diff --git a/test/simple/test-event-emitter-remove-all-listeners.js b/test/simple/test-event-emitter-remove-all-listeners.js deleted file mode 100644 index f9848d682..000000000 --- a/test/simple/test-event-emitter-remove-all-listeners.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - - -function expect(expected) { - var actual = []; - process.on('exit', function() { - assert.deepEqual(actual.sort(), expected.sort()); - }); - function listener(name) { - actual.push(name) - } - return common.mustCall(listener, expected.length); -} - -function listener() {} - -var e1 = new events.EventEmitter(); -e1.on('foo', listener); -e1.on('bar', listener); -e1.on('baz', listener); -e1.on('baz', listener); -var fooListeners = e1.listeners('foo'); -var barListeners = e1.listeners('bar'); -var bazListeners = e1.listeners('baz'); -e1.on('removeListener', expect(['bar', 'baz', 'baz'])); -e1.removeAllListeners('bar'); -e1.removeAllListeners('baz'); -assert.deepEqual(e1.listeners('foo'), [listener]); -assert.deepEqual(e1.listeners('bar'), []); -assert.deepEqual(e1.listeners('baz'), []); -// after calling removeAllListeners, -// the old listeners array should stay unchanged -assert.deepEqual(fooListeners, [listener]); -assert.deepEqual(barListeners, [listener]); -assert.deepEqual(bazListeners, [listener, listener]); -// after calling removeAllListeners, -// new listeners arrays are different from the old -assert.notEqual(e1.listeners('bar'), barListeners); -assert.notEqual(e1.listeners('baz'), bazListeners); - -var e2 = new events.EventEmitter(); -e2.on('foo', listener); -e2.on('bar', listener); -// expect LIFO order -e2.on('removeListener', expect(['foo', 'bar', 'removeListener'])); -e2.on('removeListener', expect(['foo', 'bar'])); -e2.removeAllListeners(); -console.error(e2); -assert.deepEqual([], e2.listeners('foo')); -assert.deepEqual([], e2.listeners('bar')); - -var e3 = new events.EventEmitter(); -e3.on('removeListener', listener); -// check for regression where removeAllListeners throws when -// there exists a removeListener listener, but there exists -// no listeners for the provided event type -assert.doesNotThrow(e3.removeAllListeners.bind(e3, 'foo')); diff --git a/test/simple/test-event-emitter-remove-listeners.js b/test/simple/test-event-emitter-remove-listeners.js deleted file mode 100644 index 78133a4f3..000000000 --- a/test/simple/test-event-emitter-remove-listeners.js +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var count = 0; - -function listener1() { - console.log('listener1'); - count++; -} - -function listener2() { - console.log('listener2'); - count++; -} - -function listener3() { - console.log('listener3'); - count++; -} - -function remove1() { - assert(0); -} - -function remove2() { - assert(0); -} - -var e1 = new events.EventEmitter(); -e1.on('hello', listener1); -e1.on('removeListener', common.mustCall(function(name, cb) { - assert.equal(name, 'hello'); - assert.equal(cb, listener1); -})); -e1.removeListener('hello', listener1); -assert.deepEqual([], e1.listeners('hello')); - -var e2 = new events.EventEmitter(); -e2.on('hello', listener1); -e2.on('removeListener', assert.fail); -e2.removeListener('hello', listener2); -assert.deepEqual([listener1], e2.listeners('hello')); - -var e3 = new events.EventEmitter(); -e3.on('hello', listener1); -e3.on('hello', listener2); -e3.on('removeListener', common.mustCall(function(name, cb) { - assert.equal(name, 'hello'); - assert.equal(cb, listener1); -})); -e3.removeListener('hello', listener1); -assert.deepEqual([listener2], e3.listeners('hello')); - -var e4 = new events.EventEmitter(); -e4.on('removeListener', common.mustCall(function(name, cb) { - if (cb !== remove1) return; - this.removeListener('quux', remove2); - this.emit('quux'); -}, 2)); -e4.on('quux', remove1); -e4.on('quux', remove2); -e4.removeListener('quux', remove1); diff --git a/test/simple/test-event-emitter-set-max-listeners-side-effects.js b/test/simple/test-event-emitter-set-max-listeners-side-effects.js deleted file mode 100644 index 604129796..000000000 --- a/test/simple/test-event-emitter-set-max-listeners-side-effects.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var events = require('events'); - -var e = new events.EventEmitter; - -assert.deepEqual(e._events, {}); -e.setMaxListeners(5); -assert.deepEqual(e._events, {}); diff --git a/test/simple/test-event-emitter-subclass.js b/test/simple/test-event-emitter-subclass.js deleted file mode 100644 index 60b4bf387..000000000 --- a/test/simple/test-event-emitter-subclass.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var EventEmitter = require('events').EventEmitter; -var util = require('util'); - -util.inherits(MyEE, EventEmitter); - -function MyEE(cb) { - this.once(1, cb); - this.emit(1); - this.removeAllListeners(); - EventEmitter.call(this); -} - -var called = false; -var myee = new MyEE(function() { - called = true; -}); - - -util.inherits(ErrorEE, EventEmitter); -function ErrorEE() { - this.emit('error', new Error('blerg')); -} - -assert.throws(function() { - new ErrorEE(); -}, /blerg/); - -process.on('exit', function() { - assert(called); - assert.deepEqual(myee._events, {}); - console.log('ok'); -}); - - -function MyEE2() { - EventEmitter.call(this); -} - -MyEE2.prototype = new EventEmitter(); - -var ee1 = new MyEE2(); -var ee2 = new MyEE2(); - -ee1.on('x', function () {}); - -assert.equal(EventEmitter.listenerCount(ee2, 'x'), 0); diff --git a/test/simple/test-exception-handler.js b/test/simple/test-exception-handler.js deleted file mode 100644 index 38137b834..000000000 --- a/test/simple/test-exception-handler.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var MESSAGE = 'catch me if you can'; -var caughtException = false; - -process.on('uncaughtException', function(e) { - console.log('uncaught exception! 1'); - assert.equal(MESSAGE, e.message); - caughtException = true; -}); - -process.on('uncaughtException', function(e) { - console.log('uncaught exception! 2'); - assert.equal(MESSAGE, e.message); - caughtException = true; -}); - -setTimeout(function() { - throw new Error(MESSAGE); -}, 10); - -process.on('exit', function() { - console.log('exit'); - assert.equal(true, caughtException); -}); diff --git a/test/simple/test-exception-handler2.js b/test/simple/test-exception-handler2.js deleted file mode 100644 index 6b8afa909..000000000 --- a/test/simple/test-exception-handler2.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -process.on('uncaughtException', function(err) { - console.log('Caught exception: ' + err); -}); - -var timeoutFired = false; -setTimeout(function() { - console.log('This will still run.'); - timeoutFired = true; -}, 500); - -process.on('exit', function() { - assert.ok(timeoutFired); -}); - -// Intentionally cause an exception, but don't catch it. -nonexistentFunc(); -console.log('This will not run.'); - diff --git a/test/simple/test-exec-max-buffer.js b/test/simple/test-exec-max-buffer.js deleted file mode 100644 index 3157fc73f..000000000 --- a/test/simple/test-exec-max-buffer.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var exec = require('child_process').exec; -var assert = require('assert'); - -var cmd = 'echo "hello world"'; - -exec(cmd, { maxBuffer: 5 }, function(err, stdout, stderr) { - assert.ok(err); - assert.ok(/maxBuffer/.test(err.message)); -}); diff --git a/test/simple/test-file-read-noexist.js b/test/simple/test-file-read-noexist.js deleted file mode 100644 index aa5e761b4..000000000 --- a/test/simple/test-file-read-noexist.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var got_error = false; - -var filename = path.join(common.fixturesDir, 'does_not_exist.txt'); -fs.readFile(filename, 'raw', function(err, content) { - if (err) { - got_error = true; - } else { - common.debug('cat returned some content: ' + content); - common.debug('this shouldn\'t happen as the file doesn\'t exist...'); - assert.equal(true, false); - } -}); - -process.on('exit', function() { - console.log('done'); - assert.equal(true, got_error); -}); diff --git a/test/simple/test-file-write-stream.js b/test/simple/test-file-write-stream.js deleted file mode 100644 index d4d146a84..000000000 --- a/test/simple/test-file-write-stream.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'); -var fs = require('fs'); -var fn = path.join(common.tmpDir, 'write.txt'); -var file = fs.createWriteStream(fn, { - highWaterMark: 10 - }); - -var EXPECTED = '012345678910'; - -var callbacks = { - open: -1, - drain: -2, - close: -1 - }; - -file - .on('open', function(fd) { - console.error('open!'); - callbacks.open++; - assert.equal('number', typeof fd); - }) - .on('error', function(err) { - throw err; - console.error('error!', err.stack); - }) - .on('drain', function() { - console.error('drain!', callbacks.drain); - callbacks.drain++; - if (callbacks.drain == -1) { - assert.equal(EXPECTED, fs.readFileSync(fn, 'utf8')); - file.write(EXPECTED); - } else if (callbacks.drain == 0) { - assert.equal(EXPECTED + EXPECTED, fs.readFileSync(fn, 'utf8')); - file.end(); - } - }) - .on('close', function() { - console.error('close!'); - assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); - - callbacks.close++; - assert.throws(function() { - console.error('write after end should not be allowed'); - file.write('should not work anymore'); - }); - - fs.unlinkSync(fn); - }); - -for (var i = 0; i < 11; i++) { - (function(i) { - file.write('' + i); - })(i); -} - -process.on('exit', function() { - for (var k in callbacks) { - assert.equal(0, callbacks[k], k + ' count off by ' + callbacks[k]); - } - console.log('ok'); -}); diff --git a/test/simple/test-file-write-stream2.js b/test/simple/test-file-write-stream2.js deleted file mode 100644 index 68361bb52..000000000 --- a/test/simple/test-file-write-stream2.js +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'); -var fs = require('fs'); -var util = require('util'); - - -var filepath = path.join(common.tmpDir, 'write.txt'); -var file; - -var EXPECTED = '012345678910'; - -var cb_expected = 'write open drain write drain close error '; -var cb_occurred = ''; - -var countDrains = 0; - - -process.on('exit', function() { - removeTestFile(); - if (cb_occurred !== cb_expected) { - console.log(' Test callback events missing or out of order:'); - console.log(' expected: %j', cb_expected); - console.log(' occurred: %j', cb_occurred); - assert.strictEqual(cb_occurred, cb_expected, - 'events missing or out of order: "' + - cb_occurred + '" !== "' + cb_expected + '"'); - } else { - console.log('ok'); - } -}); - -function removeTestFile() { - try { - fs.unlinkSync(filepath); - } catch (e) {} -} - - -removeTestFile(); - -// drain at 0, return false at 10. -file = fs.createWriteStream(filepath, { - highWaterMark: 11 -}); - -file.on('open', function(fd) { - console.error('open'); - cb_occurred += 'open '; - assert.equal(typeof fd, 'number'); -}); - -file.on('drain', function() { - console.error('drain'); - cb_occurred += 'drain '; - ++countDrains; - if (countDrains === 1) { - console.error('drain=1, write again'); - assert.equal(fs.readFileSync(filepath, 'utf8'), EXPECTED); - console.error('ondrain write ret=%j', file.write(EXPECTED)); - cb_occurred += 'write '; - } else if (countDrains == 2) { - console.error('second drain, end'); - assert.equal(fs.readFileSync(filepath, 'utf8'), EXPECTED + EXPECTED); - file.end(); - } -}); - -file.on('close', function() { - cb_occurred += 'close '; - assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); - file.write('should not work anymore'); -}); - - -file.on('error', function(err) { - cb_occurred += 'error '; - assert.ok(err.message.indexOf('write after end') >= 0); -}); - - -for (var i = 0; i < 11; i++) { - var ret = file.write(i + ''); - console.error('%d %j', i, ret); - - // return false when i hits 10 - assert(ret === (i != 10)); -} -cb_occurred += 'write '; diff --git a/test/simple/test-file-write-stream3.js b/test/simple/test-file-write-stream3.js deleted file mode 100644 index 013946217..000000000 --- a/test/simple/test-file-write-stream3.js +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'), - fs = require('fs'), - util = require('util'); - - -var filepath = path.join(common.tmpDir, 'write_pos.txt'); - - -var cb_expected = 'write open close write open close write open close ', - cb_occurred = ''; - -var fileDataInitial = 'abcdefghijklmnopqrstuvwxyz'; - -var fileDataExpected_1 = 'abcdefghijklmnopqrstuvwxyz'; -var fileDataExpected_2 = 'abcdefghij123456qrstuvwxyz'; -var fileDataExpected_3 = 'abcdefghij\u2026\u2026qrstuvwxyz'; - - -process.on('exit', function() { - removeTestFile(); - if (cb_occurred !== cb_expected) { - console.log(' Test callback events missing or out of order:'); - console.log(' expected: %j', cb_expected); - console.log(' occurred: %j', cb_occurred); - assert.strictEqual(cb_occurred, cb_expected, - 'events missing or out of order: "' + - cb_occurred + '" !== "' + cb_expected + '"'); - } -}); - -function removeTestFile() { - try { - fs.unlinkSync(filepath); - } catch (ex) { } -} - - -removeTestFile(); - - -function run_test_1() { - var file, buffer, options; - - options = {}; - file = fs.createWriteStream(filepath, options); - console.log(' (debug: start ', file.start); - console.log(' (debug: pos ', file.pos); - - file.on('open', function(fd) { - cb_occurred += 'open '; - }); - - file.on('close', function() { - cb_occurred += 'close '; - console.log(' (debug: bytesWritten ', file.bytesWritten); - console.log(' (debug: start ', file.start); - console.log(' (debug: pos ', file.pos); - assert.strictEqual(file.bytesWritten, buffer.length); - var fileData = fs.readFileSync(filepath, 'utf8'); - console.log(' (debug: file data ', fileData); - console.log(' (debug: expected ', fileDataExpected_1); - assert.equal(fileData, fileDataExpected_1); - - run_test_2(); - }); - - file.on('error', function(err) { - cb_occurred += 'error '; - console.log(' (debug: err event ', err); - throw err; - }); - - buffer = new Buffer(fileDataInitial); - file.write(buffer); - cb_occurred += 'write '; - - file.end(); -} - - -function run_test_2() { - var file, buffer, options; - - buffer = new Buffer('123456'); - - options = { start: 10, - flags: 'r+' }; - file = fs.createWriteStream(filepath, options); - console.log(' (debug: start ', file.start); - console.log(' (debug: pos ', file.pos); - - file.on('open', function(fd) { - cb_occurred += 'open '; - }); - - file.on('close', function() { - cb_occurred += 'close '; - console.log(' (debug: bytesWritten ', file.bytesWritten); - console.log(' (debug: start ', file.start); - console.log(' (debug: pos ', file.pos); - assert.strictEqual(file.bytesWritten, buffer.length); - var fileData = fs.readFileSync(filepath, 'utf8'); - console.log(' (debug: file data ', fileData); - console.log(' (debug: expected ', fileDataExpected_2); - assert.equal(fileData, fileDataExpected_2); - - run_test_3(); - }); - - file.on('error', function(err) { - cb_occurred += 'error '; - console.log(' (debug: err event ', err); - throw err; - }); - - file.write(buffer); - cb_occurred += 'write '; - - file.end(); -} - - -function run_test_3() { - var file, buffer, options; - - var data = '\u2026\u2026', // 3 bytes * 2 = 6 bytes in UTF-8 - fileData; - - options = { start: 10, - flags: 'r+' }; - file = fs.createWriteStream(filepath, options); - console.log(' (debug: start ', file.start); - console.log(' (debug: pos ', file.pos); - - file.on('open', function(fd) { - cb_occurred += 'open '; - }); - - file.on('close', function() { - cb_occurred += 'close '; - console.log(' (debug: bytesWritten ', file.bytesWritten); - console.log(' (debug: start ', file.start); - console.log(' (debug: pos ', file.pos); - assert.strictEqual(file.bytesWritten, data.length * 3); - fileData = fs.readFileSync(filepath, 'utf8'); - console.log(' (debug: file data ', fileData); - console.log(' (debug: expected ', fileDataExpected_3); - assert.equal(fileData, fileDataExpected_3); - - run_test_4(); - }); - - file.on('error', function(err) { - cb_occurred += 'error '; - console.log(' (debug: err event ', err); - throw err; - }); - - file.write(data, 'utf8'); - cb_occurred += 'write '; - - file.end(); -} - - -function run_test_4() { - var file, options; - - options = { start: -5, - flags: 'r+' }; - - // Error: start must be >= zero - assert.throws( - function() { - file = fs.createWriteStream(filepath, options); - }, - /start must be/ - ); - -} - -run_test_1(); diff --git a/test/simple/test-force-repl.js b/test/simple/test-force-repl.js deleted file mode 100644 index 60ba3485b..000000000 --- a/test/simple/test-force-repl.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -// spawn a node child process in "interactive" mode (force the repl) -var cp = spawn(process.execPath, ['-i']); -var gotToEnd = false; -var timeoutId = setTimeout(function() { - throw new Error('timeout!'); -}, 1000); // give node + the repl 1 second to boot up - -cp.stdout.setEncoding('utf8'); - -cp.stdout.once('data', function(b) { - clearTimeout(timeoutId); - assert.equal(b, '> '); - gotToEnd = true; - cp.kill(); -}); - -process.on('exit', function() { - assert(gotToEnd); -}); diff --git a/test/simple/test-fs-access.js b/test/simple/test-fs-access.js deleted file mode 100644 index 3aa4b849f..000000000 --- a/test/simple/test-fs-access.js +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright io.js contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var doesNotExist = __filename + '__this_should_not_exist'; -var readOnlyFile = path.join(common.tmpDir, 'read_only_file'); - -var removeFile = function(file) { - try { - fs.unlinkSync(file); - } catch (err) { - // Ignore error - } -}; - -var createReadOnlyFile = function(file) { - removeFile(file); - fs.writeFileSync(file, ''); - fs.chmodSync(file, 0444); -}; - -createReadOnlyFile(readOnlyFile); - -assert(typeof fs.F_OK === 'number'); -assert(typeof fs.R_OK === 'number'); -assert(typeof fs.W_OK === 'number'); -assert(typeof fs.X_OK === 'number'); - -fs.access(__filename, function(err) { - assert.strictEqual(err, null, 'error should not exist'); -}); - -fs.access(__filename, fs.R_OK, function(err) { - assert.strictEqual(err, null, 'error should not exist'); -}); - -fs.access(doesNotExist, function(err) { - assert.notEqual(err, null, 'error should exist'); - assert.strictEqual(err.code, 'ENOENT'); - assert.strictEqual(err.path, doesNotExist); -}); - -fs.access(readOnlyFile, fs.F_OK | fs.R_OK, function(err) { - assert.strictEqual(err, null, 'error should not exist'); -}); - -fs.access(readOnlyFile, fs.W_OK, function(err) { - assert.notEqual(err, null, 'error should exist'); - assert.strictEqual(err.path, readOnlyFile); -}); - -assert.throws(function() { - fs.access(100, fs.F_OK, function(err) {}); -}, /path must be a string/); - -assert.throws(function() { - fs.access(__filename, fs.F_OK); -}, /callback must be a function/); - -assert.doesNotThrow(function() { - fs.accessSync(__filename); -}); - -assert.doesNotThrow(function() { - var mode = fs.F_OK | fs.R_OK | fs.W_OK; - - fs.accessSync(__filename, mode); -}); - -assert.throws(function() { - fs.accessSync(doesNotExist); -}, function (err) { - return err.code === 'ENOENT' && err.path === doesNotExist; -}); - -process.on('exit', function() { - removeFile(readOnlyFile); -}); diff --git a/test/simple/test-fs-append-file-sync.js b/test/simple/test-fs-append-file-sync.js deleted file mode 100644 index 7bc6a0199..000000000 --- a/test/simple/test-fs-append-file-sync.js +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var join = require('path').join; -var fs = require('fs'); - -var currentFileData = 'ABCD'; - -var num = 220; -var data = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + - '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + - '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + - '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + - '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + - '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + - '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; - -// test that empty file will be created and have content added -var filename = join(common.tmpDir, 'append-sync.txt'); - -common.error('appending to ' + filename); -fs.appendFileSync(filename, data); - -var fileData = fs.readFileSync(filename); -console.error('filedata is a ' + typeof fileData); - -assert.equal(Buffer.byteLength(data), fileData.length); - -// test that appends data to a non empty file -var filename2 = join(common.tmpDir, 'append-sync2.txt'); -fs.writeFileSync(filename2, currentFileData); - -common.error('appending to ' + filename2); -fs.appendFileSync(filename2, data); - -var fileData2 = fs.readFileSync(filename2); - -assert.equal(Buffer.byteLength(data) + currentFileData.length, - fileData2.length); - -// test that appendFileSync accepts buffers -var filename3 = join(common.tmpDir, 'append-sync3.txt'); -fs.writeFileSync(filename3, currentFileData); - -common.error('appending to ' + filename3); - -var buf = new Buffer(data, 'utf8'); -fs.appendFileSync(filename3, buf); - -var fileData3 = fs.readFileSync(filename3); - -assert.equal(buf.length + currentFileData.length, fileData3.length); - -// test that appendFile accepts numbers. -var filename4 = join(common.tmpDir, 'append-sync4.txt'); -fs.writeFileSync(filename4, currentFileData, { mode: m }); - -common.error('appending to ' + filename4); -var m = 0600; -fs.appendFileSync(filename4, num, { mode: m }); - -// windows permissions aren't unix -if (process.platform !== 'win32') { - var st = fs.statSync(filename4); - assert.equal(st.mode & 0700, m); -} - -var fileData4 = fs.readFileSync(filename4); - -assert.equal(Buffer.byteLength('' + num) + currentFileData.length, - fileData4.length); - -//exit logic for cleanup - -process.on('exit', function() { - common.error('done'); - - fs.unlinkSync(filename); - fs.unlinkSync(filename2); - fs.unlinkSync(filename3); - fs.unlinkSync(filename4); -}); diff --git a/test/simple/test-fs-append-file.js b/test/simple/test-fs-append-file.js deleted file mode 100644 index 450c8d3b9..000000000 --- a/test/simple/test-fs-append-file.js +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var join = require('path').join; - -var filename = join(common.tmpDir, 'append.txt'); - -common.error('appending to ' + filename); - -var currentFileData = 'ABCD'; - -var n = 220; -var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + - '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + - '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + - '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + - '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + - '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + - '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; - -var ncallbacks = 0; - -// test that empty file will be created and have content added -fs.appendFile(filename, s, function(e) { - if (e) throw e; - - ncallbacks++; - common.error('appended to file'); - - fs.readFile(filename, function(e, buffer) { - if (e) throw e; - common.error('file read'); - ncallbacks++; - assert.equal(Buffer.byteLength(s), buffer.length); - }); -}); - -// test that appends data to a non empty file -var filename2 = join(common.tmpDir, 'append2.txt'); -fs.writeFileSync(filename2, currentFileData); - -fs.appendFile(filename2, s, function(e) { - if (e) throw e; - - ncallbacks++; - common.error('appended to file2'); - - fs.readFile(filename2, function(e, buffer) { - if (e) throw e; - common.error('file2 read'); - ncallbacks++; - assert.equal(Buffer.byteLength(s) + currentFileData.length, buffer.length); - }); -}); - -// test that appendFile accepts buffers -var filename3 = join(common.tmpDir, 'append3.txt'); -fs.writeFileSync(filename3, currentFileData); - -var buf = new Buffer(s, 'utf8'); -common.error('appending to ' + filename3); - -fs.appendFile(filename3, buf, function(e) { - if (e) throw e; - - ncallbacks++; - common.error('appended to file3'); - - fs.readFile(filename3, function(e, buffer) { - if (e) throw e; - common.error('file3 read'); - ncallbacks++; - assert.equal(buf.length + currentFileData.length, buffer.length); - }); -}); - -// test that appendFile accepts numbers. -var filename4 = join(common.tmpDir, 'append4.txt'); -fs.writeFileSync(filename4, currentFileData); - -common.error('appending to ' + filename4); - -var m = 0600; -fs.appendFile(filename4, n, { mode: m }, function(e) { - if (e) throw e; - - ncallbacks++; - common.error('appended to file4'); - - // windows permissions aren't unix - if (process.platform !== 'win32') { - var st = fs.statSync(filename4); - assert.equal(st.mode & 0700, m); - } - - fs.readFile(filename4, function(e, buffer) { - if (e) throw e; - common.error('file4 read'); - ncallbacks++; - assert.equal(Buffer.byteLength('' + n) + currentFileData.length, - buffer.length); - }); -}); - -process.on('exit', function() { - common.error('done'); - assert.equal(8, ncallbacks); - - fs.unlinkSync(filename); - fs.unlinkSync(filename2); - fs.unlinkSync(filename3); - fs.unlinkSync(filename4); -}); diff --git a/test/simple/test-fs-chmod.js b/test/simple/test-fs-chmod.js deleted file mode 100644 index 12fd820f3..000000000 --- a/test/simple/test-fs-chmod.js +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var got_error = false; -var success_count = 0; -var mode_async; -var mode_sync; -var is_windows = process.platform === 'win32'; - -// Need to hijack fs.open/close to make sure that things -// get closed once they're opened. -fs._open = fs.open; -fs._openSync = fs.openSync; -fs.open = open; -fs.openSync = openSync; -fs._close = fs.close; -fs._closeSync = fs.closeSync; -fs.close = close; -fs.closeSync = closeSync; - -var openCount = 0; - -function open() { - openCount++; - return fs._open.apply(fs, arguments); -} - -function openSync() { - openCount++; - return fs._openSync.apply(fs, arguments); -} - -function close() { - openCount--; - return fs._close.apply(fs, arguments); -} - -function closeSync() { - openCount--; - return fs._closeSync.apply(fs, arguments); -} - - -// On Windows chmod is only able to manipulate read-only bit -if (is_windows) { - mode_async = 0400; // read-only - mode_sync = 0600; // read-write -} else { - mode_async = 0777; - mode_sync = 0644; -} - -var file1 = path.join(common.fixturesDir, 'a.js'), - file2 = path.join(common.fixturesDir, 'a1.js'); - -fs.chmod(file1, mode_async.toString(8), function(err) { - if (err) { - got_error = true; - } else { - console.log(fs.statSync(file1).mode); - - if (is_windows) { - assert.ok((fs.statSync(file1).mode & 0777) & mode_async); - } else { - assert.equal(mode_async, fs.statSync(file1).mode & 0777); - } - - fs.chmodSync(file1, mode_sync); - if (is_windows) { - assert.ok((fs.statSync(file1).mode & 0777) & mode_sync); - } else { - assert.equal(mode_sync, fs.statSync(file1).mode & 0777); - } - success_count++; - } -}); - -fs.open(file2, 'a', function(err, fd) { - if (err) { - got_error = true; - console.error(err.stack); - return; - } - fs.fchmod(fd, mode_async.toString(8), function(err) { - if (err) { - got_error = true; - } else { - console.log(fs.fstatSync(fd).mode); - - if (is_windows) { - assert.ok((fs.fstatSync(fd).mode & 0777) & mode_async); - } else { - assert.equal(mode_async, fs.fstatSync(fd).mode & 0777); - } - - fs.fchmodSync(fd, mode_sync); - if (is_windows) { - assert.ok((fs.fstatSync(fd).mode & 0777) & mode_sync); - } else { - assert.equal(mode_sync, fs.fstatSync(fd).mode & 0777); - } - success_count++; - fs.close(fd); - } - }); -}); - -// lchmod -if (fs.lchmod) { - var link = path.join(common.tmpDir, 'symbolic-link'); - - try { - fs.unlinkSync(link); - } catch (er) {} - fs.symlinkSync(file2, link); - - fs.lchmod(link, mode_async, function(err) { - if (err) { - got_error = true; - } else { - console.log(fs.lstatSync(link).mode); - assert.equal(mode_async, fs.lstatSync(link).mode & 0777); - - fs.lchmodSync(link, mode_sync); - assert.equal(mode_sync, fs.lstatSync(link).mode & 0777); - success_count++; - } - }); -} else { - success_count++; -} - - -process.on('exit', function() { - assert.equal(3, success_count); - assert.equal(0, openCount); - assert.equal(false, got_error); -}); - diff --git a/test/simple/test-fs-empty-readStream.js b/test/simple/test-fs-empty-readStream.js deleted file mode 100644 index d181c2198..000000000 --- a/test/simple/test-fs-empty-readStream.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var emptyFile = path.join(common.fixturesDir, 'empty.txt'); - -fs.open(emptyFile, 'r', function (error, fd) { - assert.ifError(error); - - var read = fs.createReadStream(emptyFile, { 'fd': fd }); - - read.once('data', function () { - throw new Error('data event should not emit'); - }); - - var readEmit = false; - read.once('end', function () { - readEmit = true; - console.error('end event 1'); - }); - - setTimeout(function () { - assert.equal(readEmit, true); - }, 50); -}); - -fs.open(emptyFile, 'r', function (error, fd) { - assert.ifError(error); - - var read = fs.createReadStream(emptyFile, { 'fd': fd }); - read.pause(); - - read.once('data', function () { - throw new Error('data event should not emit'); - }); - - var readEmit = false; - read.once('end', function () { - readEmit = true; - console.error('end event 2'); - }); - - setTimeout(function () { - assert.equal(readEmit, false); - }, 50); -}); diff --git a/test/simple/test-fs-error-messages.js b/test/simple/test-fs-error-messages.js deleted file mode 100644 index 16b5dd92b..000000000 --- a/test/simple/test-fs-error-messages.js +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'), - fs = require('fs'), - fn = path.join(common.fixturesDir, 'non-existent'), - existingFile = path.join(common.fixturesDir, 'exit.js'), - existingFile2 = path.join(common.fixturesDir, 'create-file.js'), - existingDir = path.join(common.fixturesDir, 'empty'), - existingDir2 = path.join(common.fixturesDir, 'keys'); - -// ASYNC_CALL - -fs.stat(fn, function(err) { - assert.equal(fn, err.path); - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.lstat(fn, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.readlink(fn, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.link(fn, 'foo', function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.link(existingFile, existingFile2, function(err) { - assert.ok(0 <= err.message.indexOf(existingFile2)); -}); - -fs.symlink(existingFile, existingFile2, function(err) { - assert.ok(0 <= err.message.indexOf(existingFile2)); -}); - -fs.unlink(fn, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.rename(fn, 'foo', function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.rename(existingDir, existingDir2, function(err) { - assert.ok(0 <= err.message.indexOf(existingDir2)); -}); - -fs.rmdir(fn, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.mkdir(existingFile, 0666, function(err) { - assert.ok(0 <= err.message.indexOf(existingFile)); -}); - -fs.rmdir(existingFile, function(err) { - assert.ok(0 <= err.message.indexOf(existingFile)); -}); - -fs.chmod(fn, 0666, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.open(fn, 'r', 0666, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -fs.readFile(fn, function(err) { - assert.ok(0 <= err.message.indexOf(fn)); -}); - -// Sync - -var errors = [], - expected = 0; - -try { - ++expected; - fs.statSync(fn); -} catch (err) { - errors.push('stat'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.mkdirSync(existingFile, 0666); -} catch (err) { - errors.push('mkdir'); - assert.ok(0 <= err.message.indexOf(existingFile)); -} - -try { - ++expected; - fs.chmodSync(fn, 0666); -} catch (err) { - errors.push('chmod'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.lstatSync(fn); -} catch (err) { - errors.push('lstat'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.readlinkSync(fn); -} catch (err) { - errors.push('readlink'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.linkSync(fn, 'foo'); -} catch (err) { - errors.push('link'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.linkSync(existingFile, existingFile2); -} catch (err) { - errors.push('link'); - assert.ok(0 <= err.message.indexOf(existingFile2)); -} - -try { - ++expected; - fs.symlinkSync(existingFile, existingFile2); -} catch (err) { - errors.push('symlink'); - assert.ok(0 <= err.message.indexOf(existingFile2)); -} - -try { - ++expected; - fs.unlinkSync(fn); -} catch (err) { - errors.push('unlink'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.rmdirSync(fn); -} catch (err) { - errors.push('rmdir'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.rmdirSync(existingFile); -} catch (err) { - errors.push('rmdir'); - assert.ok(0 <= err.message.indexOf(existingFile)); -} - -try { - ++expected; - fs.openSync(fn, 'r'); -} catch (err) { - errors.push('opens'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.renameSync(fn, 'foo'); -} catch (err) { - errors.push('rename'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -try { - ++expected; - fs.renameSync(existingDir, existingDir2); -} catch (err) { - errors.push('rename'); - assert.ok(0 <= err.message.indexOf(existingDir2)); -} - -try { - ++expected; - fs.readdirSync(fn); -} catch (err) { - errors.push('readdir'); - assert.ok(0 <= err.message.indexOf(fn)); -} - -process.on('exit', function() { - assert.equal(expected, errors.length, - 'Test fs sync exceptions raised, got ' + errors.length + - ' expected ' + expected); -}); diff --git a/test/simple/test-fs-exists.js b/test/simple/test-fs-exists.js deleted file mode 100644 index 377573056..000000000 --- a/test/simple/test-fs-exists.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var f = __filename; -var exists; -var doesNotExist; - -fs.exists(f, function(y) { - exists = y; -}); - -fs.exists(f + '-NO', function(y) { - doesNotExist = y; -}); - -assert(fs.existsSync(f)); -assert(!fs.existsSync(f + '-NO')); - -process.on('exit', function() { - assert.strictEqual(exists, true); - assert.strictEqual(doesNotExist, false); -}); diff --git a/test/simple/test-fs-fsync.js b/test/simple/test-fs-fsync.js deleted file mode 100644 index e624ed7d6..000000000 --- a/test/simple/test-fs-fsync.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'); -var fs = require('fs'); -var successes = 0; - -var file = path.join(common.fixturesDir, 'a.js'); - -common.error('open ' + file); - -fs.open(file, 'a', 0777, function(err, fd) { - common.error('fd ' + fd); - if (err) throw err; - - fs.fdatasyncSync(fd); - common.error('fdatasync SYNC: ok'); - successes++; - - fs.fsyncSync(fd); - common.error('fsync SYNC: ok'); - successes++; - - fs.fdatasync(fd, function(err) { - if (err) throw err; - common.error('fdatasync ASYNC: ok'); - successes++; - fs.fsync(fd, function(err) { - if (err) throw err; - common.error('fsync ASYNC: ok'); - successes++; - }); - }); -}); - -process.on('exit', function() { - assert.equal(4, successes); -}); diff --git a/test/simple/test-fs-long-path.js b/test/simple/test-fs-long-path.js deleted file mode 100644 index 67f042976..000000000 --- a/test/simple/test-fs-long-path.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var fs = require('fs'); -var path = require('path'); -var assert = require('assert'); - -var successes = 0; - -// make a path that will be at least 260 chars long. -var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); -var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); -var fullPath = path.resolve(fileName); - -try { - fs.unlinkSync(fullPath); -} -catch (e) { - // Ignore. -} - -console.log({ - filenameLength: fileName.length, - fullPathLength: fullPath.length -}); - -fs.writeFile(fullPath, 'ok', function(err) { - if (err) throw err; - successes++; - - fs.stat(fullPath, function(err, stats) { - if (err) throw err; - successes++; - }); -}); - -process.on('exit', function() { - fs.unlinkSync(fullPath); - assert.equal(2, successes); -}); diff --git a/test/simple/test-fs-mkdir.js b/test/simple/test-fs-mkdir.js deleted file mode 100644 index d99cd371b..000000000 --- a/test/simple/test-fs-mkdir.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -function unlink(pathname) { - try { - fs.rmdirSync(pathname); - } catch (e) { - } -} - -(function() { - var ncalls = 0; - var pathname = common.tmpDir + '/test1'; - - unlink(pathname); - - fs.mkdir(pathname, function(err) { - assert.equal(err, null); - assert.equal(fs.existsSync(pathname), true); - ncalls++; - }); - - process.on('exit', function() { - unlink(pathname); - assert.equal(ncalls, 1); - }); -})(); - -(function() { - var ncalls = 0; - var pathname = common.tmpDir + '/test2'; - - unlink(pathname); - - fs.mkdir(pathname, 511 /*=0777*/, function(err) { - assert.equal(err, null); - assert.equal(fs.existsSync(pathname), true); - ncalls++; - }); - - process.on('exit', function() { - unlink(pathname); - assert.equal(ncalls, 1); - }); -})(); - -(function() { - var pathname = common.tmpDir + '/test3'; - - unlink(pathname); - fs.mkdirSync(pathname); - - var exists = fs.existsSync(pathname); - unlink(pathname); - - assert.equal(exists, true); -})(); - -// Keep the event loop alive so the async mkdir() requests -// have a chance to run (since they don't ref the event loop). -process.nextTick(function() {}); diff --git a/test/simple/test-fs-non-number-arguments-throw.js b/test/simple/test-fs-non-number-arguments-throw.js deleted file mode 100644 index 7a1e7bdb5..000000000 --- a/test/simple/test-fs-non-number-arguments-throw.js +++ /dev/null @@ -1,24 +0,0 @@ -var assert = require('assert'), - fs = require('fs'), - saneEmitter, - sanity = 'ire(\'assert\')'; - -saneEmitter = fs.createReadStream(__filename, { start: 17, end: 29 }); - -assert.throws(function () { - fs.createReadStream(__filename, { start: "17", end: 29 }); -}, "start as string didn't throw an error for createReadStream"); - -assert.throws(function () { - fs.createReadStream(__filename, { start: 17, end: "29" }); -}, "end as string didn't throw an error"); - -assert.throws(function () { - fs.createWriteStream(__filename, { start: "17" }); -}, "start as string didn't throw an error for createWriteStream"); - -saneEmitter.on('data', function (data) { - // a sanity check when using numbers instead of strings - assert.strictEqual(sanity, data.toString('utf8'), 'read ' + - data.toString('utf8') + ' instead of ' + sanity); -}); diff --git a/test/simple/test-fs-null-bytes.js b/test/simple/test-fs-null-bytes.js deleted file mode 100644 index 5dec223ba..000000000 --- a/test/simple/test-fs-null-bytes.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -function check(async, sync) { - var expected = /Path must be a string without null bytes./; - var argsSync = Array.prototype.slice.call(arguments, 2); - var argsAsync = argsSync.concat(function(er) { - assert(er && er.message.match(expected)); - }); - - if (sync) - assert.throws(function() { - console.error(sync.name, argsSync); - sync.apply(null, argsSync); - }, expected); - - if (async) - async.apply(null, argsAsync); -} - -check(fs.appendFile, fs.appendFileSync, 'foo\u0000bar'); -check(fs.chmod, fs.chmodSync, 'foo\u0000bar', '0644'); -check(fs.chown, fs.chownSync, 'foo\u0000bar', 12, 34); -check(fs.link, fs.linkSync, 'foo\u0000bar', 'foobar'); -check(fs.link, fs.linkSync, 'foobar', 'foo\u0000bar'); -check(fs.lstat, fs.lstatSync, 'foo\u0000bar'); -check(fs.mkdir, fs.mkdirSync, 'foo\u0000bar', '0755'); -check(fs.open, fs.openSync, 'foo\u0000bar', 'r'); -check(fs.readFile, fs.readFileSync, 'foo\u0000bar'); -check(fs.readdir, fs.readdirSync, 'foo\u0000bar'); -check(fs.readlink, fs.readlinkSync, 'foo\u0000bar'); -check(fs.realpath, fs.realpathSync, 'foo\u0000bar'); -check(fs.rename, fs.renameSync, 'foo\u0000bar', 'foobar'); -check(fs.rename, fs.renameSync, 'foobar', 'foo\u0000bar'); -check(fs.rmdir, fs.rmdirSync, 'foo\u0000bar'); -check(fs.stat, fs.statSync, 'foo\u0000bar'); -check(fs.symlink, fs.symlinkSync, 'foo\u0000bar', 'foobar'); -check(fs.symlink, fs.symlinkSync, 'foobar', 'foo\u0000bar'); -check(fs.truncate, fs.truncateSync, 'foo\u0000bar'); -check(fs.unlink, fs.unlinkSync, 'foo\u0000bar'); -check(null, fs.unwatchFile, 'foo\u0000bar', assert.fail); -check(fs.utimes, fs.utimesSync, 'foo\u0000bar', 0, 0); -check(null, fs.watch, 'foo\u0000bar', assert.fail); -check(null, fs.watchFile, 'foo\u0000bar', assert.fail); -check(fs.writeFile, fs.writeFileSync, 'foo\u0000bar'); - -// an 'error' for exists means that it doesn't exist. -// one of many reasons why this file is the absolute worst. -fs.exists('foo\u0000bar', function(exists) { - assert(!exists); -}); -assert(!fs.existsSync('foo\u0000bar')); - diff --git a/test/simple/test-fs-open-flags.js b/test/simple/test-fs-open-flags.js deleted file mode 100644 index e1c6c3be9..000000000 --- a/test/simple/test-fs-open-flags.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var constants = require('constants'); -var fs = require('fs'); - -var O_APPEND = constants.O_APPEND || 0; -var O_CREAT = constants.O_CREAT || 0; -var O_DIRECTORY = constants.O_DIRECTORY || 0; -var O_EXCL = constants.O_EXCL || 0; -var O_NOCTTY = constants.O_NOCTTY || 0; -var O_NOFOLLOW = constants.O_NOFOLLOW || 0; -var O_RDONLY = constants.O_RDONLY || 0; -var O_RDWR = constants.O_RDWR || 0; -var O_SYMLINK = constants.O_SYMLINK || 0; -var O_SYNC = constants.O_SYNC || 0; -var O_TRUNC = constants.O_TRUNC || 0; -var O_WRONLY = constants.O_WRONLY || 0; - -assert.equal(fs._stringToFlags('r'), O_RDONLY); -assert.equal(fs._stringToFlags('r+'), O_RDWR); -assert.equal(fs._stringToFlags('w'), O_TRUNC | O_CREAT | O_WRONLY); -assert.equal(fs._stringToFlags('w+'), O_TRUNC | O_CREAT | O_RDWR); -assert.equal(fs._stringToFlags('a'), O_APPEND | O_CREAT | O_WRONLY); -assert.equal(fs._stringToFlags('a+'), O_APPEND | O_CREAT | O_RDWR); - -assert.equal(fs._stringToFlags('wx'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(fs._stringToFlags('xw'), O_TRUNC | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(fs._stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); -assert.equal(fs._stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); -assert.equal(fs._stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(fs._stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); -assert.equal(fs._stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); -assert.equal(fs._stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); - -('+ +a +r +w rw wa war raw r++ a++ w++' + - 'x +x x+ rx rx+ wxx wax xwx xxx').split(' ').forEach(function(flags) { - assert.throws(function() { fs._stringToFlags(flags); }); -}); diff --git a/test/simple/test-fs-open.js b/test/simple/test-fs-open.js deleted file mode 100644 index e334de989..000000000 --- a/test/simple/test-fs-open.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var constants = require('constants'); -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -var caughtException = false; -try { - // should throw ENOENT, not EBADF - // see https://github.com/joyent/node/pull/1228 - fs.openSync('/path/to/file/that/does/not/exist', 'r'); -} -catch (e) { - assert.equal(e.code, 'ENOENT'); - caughtException = true; -} -assert.ok(caughtException); - -var openFd; -fs.open(__filename, 'r', function(err, fd) { - if (err) { - throw err; - } - openFd = fd; -}); - -var openFd2; -fs.open(__filename, 'rs', function(err, fd) { - if (err) { - throw err; - } - openFd2 = fd; -}); - -process.on('exit', function() { - assert.ok(openFd); - assert.ok(openFd2); -}); - diff --git a/test/simple/test-fs-read-buffer.js b/test/simple/test-fs-read-buffer.js deleted file mode 100644 index 96f700363..000000000 --- a/test/simple/test-fs-read-buffer.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'), - Buffer = require('buffer').Buffer, - fs = require('fs'), - filepath = path.join(common.fixturesDir, 'x.txt'), - fd = fs.openSync(filepath, 'r'), - expected = 'xyz\n', - bufferAsync = new Buffer(expected.length), - bufferSync = new Buffer(expected.length), - readCalled = 0; - -fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { - readCalled++; - - assert.equal(bytesRead, expected.length); - assert.deepEqual(bufferAsync, new Buffer(expected)); -}); - -var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); -assert.deepEqual(bufferSync, new Buffer(expected)); -assert.equal(r, expected.length); - -process.on('exit', function() { - assert.equal(readCalled, 1); -}); diff --git a/test/simple/test-fs-read-file-sync-hostname.js b/test/simple/test-fs-read-file-sync-hostname.js deleted file mode 100644 index 758e2aedd..000000000 --- a/test/simple/test-fs-read-file-sync-hostname.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -// test reading from hostname -if (process.platform === 'linux2') { - var hostname = fs.readFileSync('/proc/sys/kernel/hostname'); - assert.ok(hostname.length > 0); -} diff --git a/test/simple/test-fs-read-file-sync.js b/test/simple/test-fs-read-file-sync.js deleted file mode 100644 index 518d32cc1..000000000 --- a/test/simple/test-fs-read-file-sync.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var fn = path.join(common.fixturesDir, 'elipses.txt'); - -var s = fs.readFileSync(fn, 'utf8'); -for (var i = 0; i < s.length; i++) { - assert.equal('\u2026', s[i]); -} -assert.equal(10000, s.length); diff --git a/test/simple/test-fs-read-stream-err.js b/test/simple/test-fs-read-stream-err.js deleted file mode 100644 index 54aa21799..000000000 --- a/test/simple/test-fs-read-stream-err.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -var stream = fs.createReadStream(__filename, { - bufferSize: 64 -}); -var err = new Error('BAM'); - -stream.on('error', common.mustCall(function errorHandler(err_) { - console.error('error event'); - process.nextTick(function() { - assert.equal(stream.fd, null); - assert.equal(err_, err); - }); -})); - -fs.close = common.mustCall(function(fd_, cb) { - assert.equal(fd_, stream.fd); - process.nextTick(cb); -}); - -var read = fs.read; -fs.read = function() { - // first time is ok. - read.apply(fs, arguments); - // then it breaks - fs.read = function() { - var cb = arguments[arguments.length - 1]; - process.nextTick(function() { - cb(err); - }); - // and should not be called again! - fs.read = function() { - throw new Error('BOOM!'); - }; - }; -}; - -stream.on('data', function(buf) { - stream.on('data', assert.fail); // no more 'data' events should follow -}); diff --git a/test/simple/test-fs-read-stream-fd.js b/test/simple/test-fs-read-stream-fd.js deleted file mode 100644 index 835ed9727..000000000 --- a/test/simple/test-fs-read-stream-fd.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var fs = require('fs'); -var assert = require('assert'); -var path = require('path'); - -var common = require('../common'); - -var file = path.join(common.tmpDir, '/read_stream_fd_test.txt'); -var input = 'hello world'; -var output = ''; -var fd, stream; - -fs.writeFileSync(file, input); -fd = fs.openSync(file, 'r'); - -stream = fs.createReadStream(null, { fd: fd, encoding: 'utf8' }); -stream.on('data', function(data) { - output += data; -}); - -process.on('exit', function() { - fs.unlinkSync(file); - assert.equal(output, input); -}); diff --git a/test/simple/test-fs-read-stream-resume.js b/test/simple/test-fs-read-stream-resume.js deleted file mode 100644 index c3ace49e9..000000000 --- a/test/simple/test-fs-read-stream-resume.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var path = require('path'); - -var file = path.join(common.fixturesDir, 'x.txt'); -var data = ''; -var first = true; - -var stream = fs.createReadStream(file); -stream.setEncoding('utf8'); -stream.on('data', function(chunk) { - data += chunk; - if (first) { - first = false; - stream.resume(); - } -}); - -process.nextTick(function() { - stream.pause(); - setTimeout(function() { - stream.resume(); - }, 100); -}); - -process.on('exit', function() { - assert.equal(data, 'xyz\n'); -}); diff --git a/test/simple/test-fs-read-stream.js b/test/simple/test-fs-read-stream.js deleted file mode 100644 index 4d1eebb2c..000000000 --- a/test/simple/test-fs-read-stream.js +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -// TODO Improved this test. test_ca.pem is too small. A proper test would -// great a large utf8 (with multibyte chars) file and stream it in, -// performing sanity checks throughout. - -var path = require('path'); -var fs = require('fs'); -var fn = path.join(common.fixturesDir, 'elipses.txt'); -var rangeFile = path.join(common.fixturesDir, 'x.txt'); - -var callbacks = { open: 0, end: 0, close: 0 }; - -var paused = false; - -var file = fs.ReadStream(fn); - -file.on('open', function(fd) { - file.length = 0; - callbacks.open++; - assert.equal('number', typeof fd); - assert.ok(file.readable); - - // GH-535 - file.pause(); - file.resume(); - file.pause(); - file.resume(); -}); - -file.on('data', function(data) { - assert.ok(data instanceof Buffer); - assert.ok(!paused); - file.length += data.length; - - paused = true; - file.pause(); - - setTimeout(function() { - paused = false; - file.resume(); - }, 10); -}); - - -file.on('end', function(chunk) { - callbacks.end++; -}); - - -file.on('close', function() { - callbacks.close++; - - //assert.equal(fs.readFileSync(fn), fileContent); -}); - -var file3 = fs.createReadStream(fn, {encoding: 'utf8'}); -file3.length = 0; -file3.on('data', function(data) { - assert.equal('string', typeof(data)); - file3.length += data.length; - - for (var i = 0; i < data.length; i++) { - // http://www.fileformat.info/info/unicode/char/2026/index.htm - assert.equal('\u2026', data[i]); - } -}); - -file3.on('close', function() { - callbacks.close++; -}); - -process.on('exit', function() { - assert.equal(1, callbacks.open); - assert.equal(1, callbacks.end); - assert.equal(2, callbacks.close); - assert.equal(30000, file.length); - assert.equal(10000, file3.length); - console.error('ok'); -}); - -var file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); -var contentRead = ''; -file4.on('data', function(data) { - contentRead += data.toString('utf-8'); -}); -file4.on('end', function(data) { - assert.equal(contentRead, 'yz'); -}); - -var file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); -file5.data = ''; -file5.on('data', function(data) { - file5.data += data.toString('utf-8'); -}); -file5.on('end', function() { - assert.equal(file5.data, 'yz\n'); -}); - -// https://github.com/joyent/node/issues/2320 -var file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); -file6.data = ''; -file6.on('data', function(data) { - file6.data += data.toString('utf-8'); -}); -file6.on('end', function() { - assert.equal(file6.data, 'yz\n'); -}); - -assert.throws(function() { - fs.createReadStream(rangeFile, {start: 10, end: 2}); -}, /start must be <= end/); - -var stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); -stream.data = ''; - -stream.on('data', function(chunk) { - stream.data += chunk; -}); - -stream.on('end', function() { - assert.equal('x', stream.data); -}); - -// pause and then resume immediately. -var pauseRes = fs.createReadStream(rangeFile); -pauseRes.pause(); -pauseRes.resume(); - -var file7 = fs.createReadStream(rangeFile, {autoClose: false }); -file7.on('data', function() {}); -file7.on('end', function() { - process.nextTick(function() { - assert(!file7.closed); - assert(!file7.destroyed); - file7Next(); - }); -}); - -function file7Next(){ - // This will tell us if the fd is usable again or not. - file7 = fs.createReadStream(null, {fd: file7.fd, start: 0 }); - file7.data = ''; - file7.on('data', function(data) { - file7.data += data; - }); - file7.on('end', function(err) { - assert.equal(file7.data, 'xyz\n'); - }); -} - -// Just to make sure autoClose won't close the stream because of error. -var file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); -file8.on('data', function() {}); -file8.on('error', common.mustCall(function() {})); - -// Make sure stream is destroyed when file does not exist. -var file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); -file9.on('data', function() {}); -file9.on('error', common.mustCall(function() {})); - -process.on('exit', function() { - assert(file7.closed); - assert(file7.destroyed); - - assert(!file8.closed); - assert(!file8.destroyed); - assert(file8.fd); - - assert(!file9.closed); - assert(file9.destroyed); -}); diff --git a/test/simple/test-fs-read.js b/test/simple/test-fs-read.js deleted file mode 100644 index 4a90f9091..000000000 --- a/test/simple/test-fs-read.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'), - fs = require('fs'), - filepath = path.join(common.fixturesDir, 'x.txt'), - fd = fs.openSync(filepath, 'r'), - expected = 'xyz\n', - readCalled = 0; - -fs.read(fd, expected.length, 0, 'utf-8', function(err, str, bytesRead) { - readCalled++; - - assert.ok(!err); - assert.equal(str, expected); - assert.equal(bytesRead, expected.length); -}); - -var r = fs.readSync(fd, expected.length, 0, 'utf-8'); -assert.equal(r[0], expected); -assert.equal(r[1], expected.length); - -process.on('exit', function() { - assert.equal(readCalled, 1); -}); diff --git a/test/simple/test-fs-readfile-empty.js b/test/simple/test-fs-readfile-empty.js deleted file mode 100644 index 31b83567e..000000000 --- a/test/simple/test-fs-readfile-empty.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'), - fs = require('fs'), - fn = path.join(common.fixturesDir, 'empty.txt'); - -fs.readFile(fn, function(err, data) { - assert.ok(data); -}); - -fs.readFile(fn, 'utf8', function(err, data) { - assert.strictEqual('', data); -}); - -assert.ok(fs.readFileSync(fn)); -assert.strictEqual('', fs.readFileSync(fn, 'utf8')); diff --git a/test/simple/test-fs-readfile-error.js b/test/simple/test-fs-readfile-error.js deleted file mode 100644 index 72e1e2e7f..000000000 --- a/test/simple/test-fs-readfile-error.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; -var path = require('path'); - -var callbacks = 0; - -function test(env, cb) { - var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js'); - var execPath = process.execPath + ' ' + filename; - var options = { env: env || {} }; - exec(execPath, options, function(err, stdout, stderr) { - assert(err); - assert.equal(stdout, ''); - assert.notEqual(stderr, ''); - cb('' + stderr); - }); -} - -test({ NODE_DEBUG: '' }, function(data) { - assert(/EISDIR/.test(data)); - assert(!/test-fs-readfile-error/.test(data)); - callbacks++; -}); - -test({ NODE_DEBUG: 'fs' }, function(data) { - assert(/EISDIR/.test(data)); - assert(/test-fs-readfile-error/.test(data)); - callbacks++; -}); - -process.on('exit', function() { - assert.equal(callbacks, 2); -}); diff --git a/test/simple/test-fs-readfile-pipe.js b/test/simple/test-fs-readfile-pipe.js deleted file mode 100644 index 8ca165144..000000000 --- a/test/simple/test-fs-readfile-pipe.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// simulate `cat readfile.js | node readfile.js` - -// TODO: Have some way to make this work on windows. -if (process.platform === 'win32') { - console.error('No /dev/stdin on windows. Skipping test.'); - process.exit(); -} - -var fs = require('fs'); - -var dataExpected = fs.readFileSync(__filename, 'utf8'); - -if (process.argv[2] === 'child') { - fs.readFile('/dev/stdin', function(er, data) { - if (er) throw er; - process.stdout.write(data); - }); - return; -} - -var exec = require('child_process').exec; -var f = JSON.stringify(__filename); -var node = JSON.stringify(process.execPath); -var cmd = 'cat ' + f + ' | ' + node + ' ' + f + ' child'; -exec(cmd, function(err, stdout, stderr) { - if (err) console.error(err); - assert(!err, 'it exits normally'); - assert(stdout === dataExpected, 'it reads the file and outputs it'); - assert(stderr === '', 'it does not write to stderr'); - console.log('ok'); -}); diff --git a/test/simple/test-fs-readfile-unlink.js b/test/simple/test-fs-readfile-unlink.js deleted file mode 100644 index 0bb4a67f7..000000000 --- a/test/simple/test-fs-readfile-unlink.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'), - common = require('../common'), - fs = require('fs'), - path = require('path'), - dirName = path.resolve(common.fixturesDir, 'test-readfile-unlink'), - fileName = path.resolve(dirName, 'test.bin'); - -var buf = new Buffer(512 * 1024); -buf.fill(42); - -try { - fs.mkdirSync(dirName); -} catch (e) { - // Ignore if the directory already exists. - if (e.code != 'EEXIST') throw e; -} - -fs.writeFileSync(fileName, buf); - -fs.readFile(fileName, function(err, data) { - assert.ifError(err); - assert(data.length == buf.length); - assert.strictEqual(buf[0], 42); - - fs.unlinkSync(fileName); - fs.rmdirSync(dirName); -}); diff --git a/test/simple/test-fs-readfile-zero-byte-liar.js b/test/simple/test-fs-readfile-zero-byte-liar.js deleted file mode 100644 index 60f41226f..000000000 --- a/test/simple/test-fs-readfile-zero-byte-liar.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -var dataExpected = fs.readFileSync(__filename, 'utf8'); - -// sometimes stat returns size=0, but it's a lie. -fs._fstat = fs.fstat; -fs._fstatSync = fs.fstatSync; - -fs.fstat = function(fd, cb) { - fs._fstat(fd, function(er, st) { - if (er) return cb(er); - st.size = 0; - return cb(er, st); - }); -}; - -fs.fstatSync = function(fd) { - var st = fs._fstatSync; - st.size = 0; - return st; -}; - -var d = fs.readFileSync(__filename, 'utf8'); -assert.equal(d, dataExpected); - -var called = false; -fs.readFile(__filename, 'utf8', function (er, d) { - assert.equal(d, dataExpected); - called = true; -}); - -process.on('exit', function() { - assert(called); - console.log("ok"); -}); diff --git a/test/simple/test-fs-realpath.js b/test/simple/test-fs-realpath.js deleted file mode 100644 index 0c820907d..000000000 --- a/test/simple/test-fs-realpath.js +++ /dev/null @@ -1,610 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var exec = require('child_process').exec; -var async_completed = 0, async_expected = 0, unlink = []; -var isWindows = process.platform === 'win32'; -var skipSymlinks = false; - -var root = '/'; -if (isWindows) { - // something like "C:\\" - root = process.cwd().substr(0, 3); - - // On Windows, creating symlinks requires admin privileges. - // We'll only try to run symlink test if we have enough privileges. - try { - exec('whoami /priv', function(err, o) { - if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { - skipSymlinks = true; - } - runTest(); - }); - } catch (er) { - // better safe than sorry - skipSymlinks = true; - process.nextTick(runTest); - } -} else { - process.nextTick(runTest); -} - - -function tmp(p) { - return path.join(common.tmpDir, p); -} - -var fixturesAbsDir = common.fixturesDir; -var tmpAbsDir = common.tmpDir; - -console.error("absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir); - -function asynctest(testBlock, args, callback, assertBlock) { - async_expected++; - testBlock.apply(testBlock, args.concat(function(err) { - var ignoreError = false; - if (assertBlock) { - try { - ignoreError = assertBlock.apply(assertBlock, arguments); - } - catch (e) { - err = e; - } - } - async_completed++; - callback(ignoreError ? null : err); - })); -} - -// sub-tests: -function test_simple_error_callback(cb) { - var ncalls = 0; - - fs.realpath('/this/path/does/not/exist', function(err, s) { - assert(err); - assert(!s); - ncalls++; - cb(); - }); - - process.on('exit', function() { - assert.equal(ncalls, 1); - }); -} - -function test_simple_relative_symlink(callback) { - console.log('test_simple_relative_symlink'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - var entry = common.tmpDir + '/symlink', - expected = common.tmpDir + '/cycles/root.js'; - [ - [entry, '../tmp/cycles/root.js'] - ].forEach(function(t) { - try {fs.unlinkSync(t[0]);}catch (e) {} - console.log('fs.symlinkSync(%j, %j, %j)', t[1], t[0], 'file'); - fs.symlinkSync(t[1], t[0], 'file'); - unlink.push(t[0]); - }); - var result = fs.realpathSync(entry); - assert.equal(result, path.resolve(expected), - 'got ' + common.inspect(result) + ' expected ' + - common.inspect(expected)); - asynctest(fs.realpath, [entry], callback, function(err, result) { - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(expected)); - }); -} - -function test_simple_absolute_symlink(callback) { - console.log('test_simple_absolute_symlink'); - - // this one should still run, even if skipSymlinks is set, - // because it uses a junction. - var type = skipSymlinks ? 'junction' : 'dir'; - - console.log('using type=%s', type); - - var entry = tmpAbsDir + '/symlink', - expected = fixturesAbsDir + '/nested-index/one'; - [ - [entry, expected] - ].forEach(function(t) { - try {fs.unlinkSync(t[0]);} catch (e) {} - console.error('fs.symlinkSync(%j, %j, %j)', t[1], t[0], type); - fs.symlinkSync(t[1], t[0], type); - unlink.push(t[0]); - }); - var result = fs.realpathSync(entry); - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(expected)); - asynctest(fs.realpath, [entry], callback, function(err, result) { - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(expected)); - }); -} - -function test_deep_relative_file_symlink(callback) { - console.log('test_deep_relative_file_symlink'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - - var expected = path.join(common.fixturesDir, 'cycles', 'root.js'); - var linkData1 = '../../cycles/root.js'; - var linkPath1 = path.join(common.fixturesDir, - 'nested-index', 'one', 'symlink1.js'); - try {fs.unlinkSync(linkPath1);} catch (e) {} - fs.symlinkSync(linkData1, linkPath1, 'file'); - - var linkData2 = '../one/symlink1.js'; - var entry = path.join(common.fixturesDir, - 'nested-index', 'two', 'symlink1-b.js'); - try {fs.unlinkSync(entry);} catch (e) {} - fs.symlinkSync(linkData2, entry, 'file'); - unlink.push(linkPath1); - unlink.push(entry); - - assert.equal(fs.realpathSync(entry), path.resolve(expected)); - asynctest(fs.realpath, [entry], callback, function(err, result) { - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(path.resolve(expected))); - }); -} - -function test_deep_relative_dir_symlink(callback) { - console.log('test_deep_relative_dir_symlink'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - var expected = path.join(common.fixturesDir, 'cycles', 'folder'); - var linkData1b = '../../cycles/folder'; - var linkPath1b = path.join(common.fixturesDir, - 'nested-index', 'one', 'symlink1-dir'); - try {fs.unlinkSync(linkPath1b);} catch (e) {} - fs.symlinkSync(linkData1b, linkPath1b, 'dir'); - - var linkData2b = '../one/symlink1-dir'; - var entry = path.join(common.fixturesDir, - 'nested-index', 'two', 'symlink12-dir'); - try {fs.unlinkSync(entry);} catch (e) {} - fs.symlinkSync(linkData2b, entry, 'dir'); - unlink.push(linkPath1b); - unlink.push(entry); - - assert.equal(fs.realpathSync(entry), path.resolve(expected)); - - asynctest(fs.realpath, [entry], callback, function(err, result) { - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(path.resolve(expected))); - }); -} - -function test_cyclic_link_protection(callback) { - console.log('test_cyclic_link_protection'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - var entry = common.tmpDir + '/cycles/realpath-3a'; - [ - [entry, '../cycles/realpath-3b'], - [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], - [common.tmpDir + '/cycles/realpath-3c', '../cycles/realpath-3a'] - ].forEach(function(t) { - try {fs.unlinkSync(t[0]);} catch (e) {} - fs.symlinkSync(t[1], t[0], 'dir'); - unlink.push(t[0]); - }); - assert.throws(function() { fs.realpathSync(entry); }); - asynctest(fs.realpath, [entry], callback, function(err, result) { - assert.ok(err && true); - return true; - }); -} - -function test_cyclic_link_overprotection(callback) { - console.log('test_cyclic_link_overprotection'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - var cycles = common.tmpDir + '/cycles'; - var expected = fs.realpathSync(cycles); - var folder = cycles + '/folder'; - var link = folder + '/cycles'; - var testPath = cycles; - for (var i = 0; i < 10; i++) testPath += '/folder/cycles'; - try {fs.unlinkSync(link)} catch (ex) {} - fs.symlinkSync(cycles, link, 'dir'); - unlink.push(link); - assert.equal(fs.realpathSync(testPath), path.resolve(expected)); - asynctest(fs.realpath, [testPath], callback, function(er, res) { - assert.equal(res, path.resolve(expected)); - }); -} - -function test_relative_input_cwd(callback) { - console.log('test_relative_input_cwd'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - - // we need to get the relative path to the tmp dir from cwd. - // When the test runner is running it, that will be .../node/test - // but it's more common to run `./node test/.../`, so detect it here. - var entrydir = process.cwd(); - var entry = common.tmpDir.substr(entrydir.length + 1) + '/cycles/realpath-3a'; - var expected = common.tmpDir + '/cycles/root.js'; - [ - [entry, '../cycles/realpath-3b'], - [common.tmpDir + '/cycles/realpath-3b', '../cycles/realpath-3c'], - [common.tmpDir + '/cycles/realpath-3c', 'root.js'] - ].forEach(function(t) { - var fn = t[0]; - console.error('fn=%j', fn); - try {fs.unlinkSync(fn);} catch (e) {} - var b = path.basename(t[1]); - var type = (b === 'root.js' ? 'file' : 'dir'); - console.log('fs.symlinkSync(%j, %j, %j)', t[1], fn, type); - fs.symlinkSync(t[1], fn, 'file'); - unlink.push(fn); - }); - - var origcwd = process.cwd(); - process.chdir(entrydir); - assert.equal(fs.realpathSync(entry), path.resolve(expected)); - asynctest(fs.realpath, [entry], callback, function(err, result) { - process.chdir(origcwd); - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(path.resolve(expected))); - return true; - }); -} - -function test_deep_symlink_mix(callback) { - console.log('test_deep_symlink_mix'); - if (isWindows) { - // This one is a mix of files and directories, and it's quite tricky - // to get the file/dir links sorted out correctly. - console.log('skipping symlink test (no way to work on windows)'); - return runNextTest(); - } - - // todo: check to see that common.fixturesDir is not rooted in the - // same directory as our test symlink. - /* - /tmp/node-test-realpath-f1 -> ../tmp/node-test-realpath-d1/foo - /tmp/node-test-realpath-d1 -> ../node-test-realpath-d2 - /tmp/node-test-realpath-d2/foo -> ../node-test-realpath-f2 - /tmp/node-test-realpath-f2 - -> /node/test/fixtures/nested-index/one/realpath-c - /node/test/fixtures/nested-index/one/realpath-c - -> /node/test/fixtures/nested-index/two/realpath-c - /node/test/fixtures/nested-index/two/realpath-c -> ../../cycles/root.js - /node/test/fixtures/cycles/root.js (hard) - */ - var entry = tmp('node-test-realpath-f1'); - try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {} - try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {} - fs.mkdirSync(tmp('node-test-realpath-d2'), 0700); - try { - [ - [entry, '../tmp/node-test-realpath-d1/foo'], - [tmp('node-test-realpath-d1'), '../tmp/node-test-realpath-d2'], - [tmp('node-test-realpath-d2/foo'), '../node-test-realpath-f2'], - [tmp('node-test-realpath-f2'), fixturesAbsDir + - '/nested-index/one/realpath-c'], - [fixturesAbsDir + '/nested-index/one/realpath-c', fixturesAbsDir + - '/nested-index/two/realpath-c'], - [fixturesAbsDir + '/nested-index/two/realpath-c', - '../../../tmp/cycles/root.js'] - ].forEach(function(t) { - //common.debug('setting up '+t[0]+' -> '+t[1]); - try { fs.unlinkSync(t[0]); } catch (e) {} - fs.symlinkSync(t[1], t[0]); - unlink.push(t[0]); - }); - } finally { - unlink.push(tmp('node-test-realpath-d2')); - } - var expected = tmpAbsDir + '/cycles/root.js'; - assert.equal(fs.realpathSync(entry), path.resolve(expected)); - asynctest(fs.realpath, [entry], callback, function(err, result) { - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(path.resolve(expected))); - return true; - }); -} - -function test_non_symlinks(callback) { - console.log('test_non_symlinks'); - var entrydir = path.dirname(tmpAbsDir); - var entry = tmpAbsDir.substr(entrydir.length + 1) + '/cycles/root.js'; - var expected = tmpAbsDir + '/cycles/root.js'; - var origcwd = process.cwd(); - process.chdir(entrydir); - assert.equal(fs.realpathSync(entry), path.resolve(expected)); - asynctest(fs.realpath, [entry], callback, function(err, result) { - process.chdir(origcwd); - assert.equal(result, path.resolve(expected), - 'got ' + - common.inspect(result) + - ' expected ' + - common.inspect(path.resolve(expected))); - return true; - }); -} - -var upone = path.join(process.cwd(), '..'); -function test_escape_cwd(cb) { - console.log('test_escape_cwd'); - asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) { - assert.equal(upone, uponeActual, - 'realpath("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); - }); -} -var uponeActual = fs.realpathSync('..'); -assert.equal(upone, uponeActual, - 'realpathSync("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); - - -// going up with .. multiple times -// . -// `-- a/ -// |-- b/ -// | `-- e -> .. -// `-- d -> .. -// realpath(a/b/e/d/a/b/e/d/a) ==> a -function test_up_multiple(cb) { - console.error('test_up_multiple'); - if (skipSymlinks) { - console.log('skipping symlink test (no privs)'); - return runNextTest(); - } - function cleanup() { - ['a/b', - 'a' - ].forEach(function(folder) { - try {fs.rmdirSync(tmp(folder))} catch (ex) {} - }); - } - function setup() { - cleanup(); - } - setup(); - fs.mkdirSync(tmp('a'), 0755); - fs.mkdirSync(tmp('a/b'), 0755); - fs.symlinkSync('..', tmp('a/d'), 'dir'); - unlink.push(tmp('a/d')); - fs.symlinkSync('..', tmp('a/b/e'), 'dir'); - unlink.push(tmp('a/b/e')); - - var abedabed = tmp('abedabed'.split('').join('/')); - var abedabed_real = tmp(''); - - var abedabeda = tmp('abedabeda'.split('').join('/')); - var abedabeda_real = tmp('a'); - - assert.equal(fs.realpathSync(abedabeda), abedabeda_real); - assert.equal(fs.realpathSync(abedabed), abedabed_real); - fs.realpath(abedabeda, function (er, real) { - if (er) throw er; - assert.equal(abedabeda_real, real); - fs.realpath(abedabed, function (er, real) { - if (er) throw er; - assert.equal(abedabed_real, real); - cb(); - cleanup(); - }); - }); -} - - -// absolute symlinks with children. -// . -// `-- a/ -// |-- b/ -// | `-- c/ -// | `-- x.txt -// `-- link -> /tmp/node-test-realpath-abs-kids/a/b/ -// realpath(root+'/a/link/c/x.txt') ==> root+'/a/b/c/x.txt' -function test_abs_with_kids(cb) { - console.log('test_abs_with_kids'); - - // this one should still run, even if skipSymlinks is set, - // because it uses a junction. - var type = skipSymlinks ? 'junction' : 'dir'; - - console.log('using type=%s', type); - - var root = tmpAbsDir + '/node-test-realpath-abs-kids'; - function cleanup() { - ['/a/b/c/x.txt', - '/a/link' - ].forEach(function(file) { - try {fs.unlinkSync(root + file)} catch (ex) {} - }); - ['/a/b/c', - '/a/b', - '/a', - '' - ].forEach(function(folder) { - try {fs.rmdirSync(root + folder)} catch (ex) {} - }); - } - function setup() { - cleanup(); - ['', - '/a', - '/a/b', - '/a/b/c' - ].forEach(function(folder) { - console.log('mkdir ' + root + folder); - fs.mkdirSync(root + folder, 0700); - }); - fs.writeFileSync(root + '/a/b/c/x.txt', 'foo'); - fs.symlinkSync(root + '/a/b', root + '/a/link', type); - } - setup(); - var linkPath = root + '/a/link/c/x.txt'; - var expectPath = root + '/a/b/c/x.txt'; - var actual = fs.realpathSync(linkPath); - // console.log({link:linkPath,expect:expectPath,actual:actual},'sync'); - assert.equal(actual, path.resolve(expectPath)); - asynctest(fs.realpath, [linkPath], cb, function(er, actual) { - // console.log({link:linkPath,expect:expectPath,actual:actual},'async'); - assert.equal(actual, path.resolve(expectPath)); - cleanup(); - }); -} - -function test_lying_cache_liar(cb) { - var n = 2; - - // this should not require *any* stat calls, since everything - // checked by realpath will be found in the cache. - console.log('test_lying_cache_liar'); - var cache = { '/foo/bar/baz/bluff' : '/foo/bar/bluff', - '/1/2/3/4/5/6/7' : '/1', - '/a' : '/a', - '/a/b' : '/a/b', - '/a/b/c' : '/a/b', - '/a/b/d' : '/a/b/d' }; - if (isWindows) { - var wc = {}; - Object.keys(cache).forEach(function(k) { - wc[ path.resolve(k) ] = path.resolve(cache[k]); - }); - cache = wc; - } - - var bluff = path.resolve('/foo/bar/baz/bluff'); - var rps = fs.realpathSync(bluff, cache); - assert.equal(cache[bluff], rps); - var nums = path.resolve('/1/2/3/4/5/6/7'); - var called = false; // no sync cb calling! - fs.realpath(nums, cache, function(er, rp) { - called = true; - assert.equal(cache[nums], rp); - if (--n === 0) cb(); - }); - assert(called === false); - - var test = path.resolve('/a/b/c/d'), - expect = path.resolve('/a/b/d'); - var actual = fs.realpathSync(test, cache); - assert.equal(expect, actual); - fs.realpath(test, cache, function(er, actual) { - assert.equal(expect, actual); - if (--n === 0) cb(); - }); -} - -// ---------------------------------------------------------------------------- - -var tests = [ - test_simple_error_callback, - test_simple_relative_symlink, - test_simple_absolute_symlink, - test_deep_relative_file_symlink, - test_deep_relative_dir_symlink, - test_cyclic_link_protection, - test_cyclic_link_overprotection, - test_relative_input_cwd, - test_deep_symlink_mix, - test_non_symlinks, - test_escape_cwd, - test_abs_with_kids, - test_lying_cache_liar, - test_up_multiple -]; -var numtests = tests.length; -var testsRun = 0; -function runNextTest(err) { - if (err) throw err; - var test = tests.shift(); - if (!test) { - return console.log(numtests + - ' subtests completed OK for fs.realpath'); - } - testsRun++; - test(runNextTest); -} - - -assert.equal(root, fs.realpathSync('/')); -fs.realpath('/', function(err, result) { - assert.equal(null, err); - assert.equal(root, result); -}); - - -function runTest() { - var tmpDirs = ['cycles', 'cycles/folder']; - tmpDirs.forEach(function(t) { - t = tmp(t); - var s; - try { s = fs.statSync(t); } catch (ex) {} - if (s) return; - fs.mkdirSync(t, 0700); - }); - fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); - console.error('start tests'); - runNextTest(); -} - - -process.on('exit', function() { - assert.equal(numtests, testsRun); - unlink.forEach(function(path) { try {fs.unlinkSync(path);} catch (e) {} }); - assert.equal(async_completed, async_expected); -}); diff --git a/test/simple/test-fs-sir-writes-alot.js b/test/simple/test-fs-sir-writes-alot.js deleted file mode 100644 index e16f56bdc..000000000 --- a/test/simple/test-fs-sir-writes-alot.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var fs = require('fs'); -var assert = require('assert'); -var join = require('path').join; - -var filename = join(common.tmpDir, 'out.txt'); - -try { - fs.unlinkSync(filename); -} catch (e) { - // might not exist, that's okay. -} - -var fd = fs.openSync(filename, 'w'); - -var line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; - -var N = 10240, complete = 0; -for (var i = 0; i < N; i++) { - // Create a new buffer for each write. Before the write is actually - // executed by the thread pool, the buffer will be collected. - var buffer = new Buffer(line); - fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { - complete++; - if (complete === N) { - fs.closeSync(fd); - var s = fs.createReadStream(filename); - s.on('data', testBuffer); - } - }); -} - -var bytesChecked = 0; - -function testBuffer(b) { - for (var i = 0; i < b.length; i++) { - bytesChecked++; - if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) { - throw new Error('invalid char ' + i + ',' + b[i]); - } - } -} - -process.on('exit', function() { - // Probably some of the writes are going to overlap, so we can't assume - // that we get (N * line.length). Let's just make sure we've checked a - // few... - assert.ok(bytesChecked > 1000); -}); - diff --git a/test/simple/test-fs-stat.js b/test/simple/test-fs-stat.js deleted file mode 100644 index 8c5a9c64c..000000000 --- a/test/simple/test-fs-stat.js +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var got_error = false; -var success_count = 0; - -fs.stat('.', function(err, stats) { - if (err) { - got_error = true; - } else { - console.dir(stats); - assert.ok(stats.mtime instanceof Date); - success_count++; - } - assert(this === global); -}); - -fs.stat('.', function(err, stats) { - assert.ok(stats.hasOwnProperty('blksize')); - assert.ok(stats.hasOwnProperty('blocks')); -}); - -fs.lstat('.', function(err, stats) { - if (err) { - got_error = true; - } else { - console.dir(stats); - assert.ok(stats.mtime instanceof Date); - success_count++; - } - assert(this === global); -}); - -// fstat -fs.open('.', 'r', undefined, function(err, fd) { - assert.ok(!err); - assert.ok(fd); - - fs.fstat(fd, function(err, stats) { - if (err) { - got_error = true; - } else { - console.dir(stats); - assert.ok(stats.mtime instanceof Date); - success_count++; - fs.close(fd); - } - assert(this === global); - }); - - assert(this === global); -}); - -// fstatSync -fs.open('.', 'r', undefined, function(err, fd) { - var stats; - try { - stats = fs.fstatSync(fd); - } catch (err) { - got_error = true; - } - if (stats) { - console.dir(stats); - assert.ok(stats.mtime instanceof Date); - success_count++; - } - fs.close(fd); -}); - -console.log('stating: ' + __filename); -fs.stat(__filename, function(err, s) { - if (err) { - got_error = true; - } else { - console.dir(s); - success_count++; - - console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); - assert.equal(false, s.isDirectory()); - - console.log('isFile: ' + JSON.stringify(s.isFile())); - assert.equal(true, s.isFile()); - - console.log('isSocket: ' + JSON.stringify(s.isSocket())); - assert.equal(false, s.isSocket()); - - console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); - assert.equal(false, s.isBlockDevice()); - - console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); - assert.equal(false, s.isCharacterDevice()); - - console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); - assert.equal(false, s.isFIFO()); - - console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); - assert.equal(false, s.isSymbolicLink()); - - assert.ok(s.mtime instanceof Date); - } -}); - -process.on('exit', function() { - assert.equal(5, success_count); - assert.equal(false, got_error); -}); - diff --git a/test/simple/test-fs-stream-double-close.js b/test/simple/test-fs-stream-double-close.js deleted file mode 100644 index 89386b6e6..000000000 --- a/test/simple/test-fs-stream-double-close.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -test1(fs.createReadStream(__filename)); -test2(fs.createReadStream(__filename)); -test3(fs.createReadStream(__filename)); - -test1(fs.createWriteStream(common.tmpDir + '/dummy1')); -test2(fs.createWriteStream(common.tmpDir + '/dummy2')); -test3(fs.createWriteStream(common.tmpDir + '/dummy3')); - -function test1(stream) { - stream.destroy(); - stream.destroy(); -} - -function test2(stream) { - stream.destroy(); - stream.on('open', function(fd) { - stream.destroy(); - open_cb_called++; - }); - process.on('exit', function() { - assert.equal(open_cb_called, 1); - }); - var open_cb_called = 0; -} - -function test3(stream) { - stream.on('open', function(fd) { - stream.destroy(); - stream.destroy(); - open_cb_called++; - }); - process.on('exit', function() { - assert.equal(open_cb_called, 1); - }); - var open_cb_called = 0; -} diff --git a/test/simple/test-fs-symlink-dir-junction-relative.js b/test/simple/test-fs-symlink-dir-junction-relative.js deleted file mode 100644 index c598d2e92..000000000 --- a/test/simple/test-fs-symlink-dir-junction-relative.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Test creating and resolving relative junction or symbolic link - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var completed = 0; -var expected_tests = 2; - -var linkPath1 = path.join(common.tmpDir, 'junction1'); -var linkPath2 = path.join(common.tmpDir, 'junction2'); -var linkTarget = path.join(common.fixturesDir); -var linkData = '../fixtures'; - -// Prepare. -try { fs.mkdirSync(common.tmpDir); } catch (e) {} -try { fs.unlinkSync(linkPath1); } catch (e) {} -try { fs.unlinkSync(linkPath2); } catch (e) {} - -// Test fs.symlink() -fs.symlink(linkData, linkPath1, 'junction', function(err) { - if (err) throw err; - verifyLink(linkPath1); -}); - -// Test fs.symlinkSync() -fs.symlinkSync(linkData, linkPath2, 'junction'); -verifyLink(linkPath2); - -function verifyLink(linkPath) { - var stats = fs.lstatSync(linkPath); - assert.ok(stats.isSymbolicLink()); - - var data1 = fs.readFileSync(linkPath + '/x.txt', 'ascii'); - var data2 = fs.readFileSync(linkTarget + '/x.txt', 'ascii'); - assert.strictEqual(data1, data2); - - // Clean up. - fs.unlinkSync(linkPath); - - completed++; -} - -process.on('exit', function() { - assert.equal(completed, expected_tests); -}); - diff --git a/test/simple/test-fs-symlink-dir-junction.js b/test/simple/test-fs-symlink-dir-junction.js deleted file mode 100644 index c675b920e..000000000 --- a/test/simple/test-fs-symlink-dir-junction.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var completed = 0; -var expected_tests = 4; - -// test creating and reading symbolic link -var linkData = path.join(common.fixturesDir, 'cycles/'); -var linkPath = path.join(common.tmpDir, 'cycles_link'); - -// Delete previously created link -try { - fs.unlinkSync(linkPath); -} catch (e) {} - -console.log('linkData: ' + linkData); -console.log('linkPath: ' + linkPath); - -fs.symlink(linkData, linkPath, 'junction', function(err) { - if (err) throw err; - completed++; - - fs.lstat(linkPath, function(err, stats) { - if (err) throw err; - assert.ok(stats.isSymbolicLink()); - completed++; - - fs.readlink(linkPath, function(err, destination) { - if (err) throw err; - assert.equal(destination, linkData); - completed++; - - fs.unlink(linkPath, function(err) { - if (err) throw err; - assert(!fs.existsSync(linkPath)); - assert(fs.existsSync(linkData)); - completed++; - }); - }); - }); -}); - -process.on('exit', function() { - assert.equal(completed, expected_tests); -}); - diff --git a/test/simple/test-fs-symlink.js b/test/simple/test-fs-symlink.js deleted file mode 100644 index 6b23b1e1c..000000000 --- a/test/simple/test-fs-symlink.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var exec = require('child_process').exec; -var completed = 0; -var expected_tests = 2; - -var is_windows = process.platform === 'win32'; - -var runtest = function(skip_symlinks) { - if (!skip_symlinks) { - // test creating and reading symbolic link - var linkData = path.join(common.fixturesDir, '/cycles/root.js'); - var linkPath = path.join(common.tmpDir, 'symlink1.js'); - - // Delete previously created link - try { - fs.unlinkSync(linkPath); - } catch (e) {} - - fs.symlink(linkData, linkPath, function(err) { - if (err) throw err; - console.log('symlink done'); - // todo: fs.lstat? - fs.readlink(linkPath, function(err, destination) { - if (err) throw err; - assert.equal(destination, linkData); - completed++; - }); - }); - } - - // test creating and reading hard link - var srcPath = path.join(common.fixturesDir, 'cycles', 'root.js'); - var dstPath = path.join(common.tmpDir, 'link1.js'); - - // Delete previously created link - try { - fs.unlinkSync(dstPath); - } catch (e) {} - - fs.link(srcPath, dstPath, function(err) { - if (err) throw err; - console.log('hard link done'); - var srcContent = fs.readFileSync(srcPath, 'utf8'); - var dstContent = fs.readFileSync(dstPath, 'utf8'); - assert.equal(srcContent, dstContent); - completed++; - }); -}; - -if (is_windows) { - // On Windows, creating symlinks requires admin privileges. - // We'll only try to run symlink test if we have enough privileges. - exec('whoami /priv', function(err, o) { - if (err || o.indexOf('SeCreateSymbolicLinkPrivilege') == -1) { - expected_tests = 1; - runtest(true); - } else { - runtest(false); - } - }); -} else { - runtest(false); -} - -process.on('exit', function() { - assert.equal(completed, expected_tests); -}); - diff --git a/test/simple/test-fs-sync-fd-leak.js b/test/simple/test-fs-sync-fd-leak.js deleted file mode 100644 index fe932c7df..000000000 --- a/test/simple/test-fs-sync-fd-leak.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -// ensure that (read|write|append)FileSync() closes the file descriptor -fs.openSync = function() { - return 42; -}; -fs.closeSync = function(fd) { - assert.equal(fd, 42); - close_called++; -}; -fs.readSync = function() { - throw new Error('BAM'); -}; -fs.writeSync = function() { - throw new Error('BAM'); -}; - -fs.fstatSync = function() { - throw new Error('BAM'); -}; - -ensureThrows(function() { - fs.readFileSync('dummy'); -}); -ensureThrows(function() { - fs.writeFileSync('dummy', 'xxx'); -}); -ensureThrows(function() { - fs.appendFileSync('dummy', 'xxx'); -}); - -var close_called = 0; -function ensureThrows(cb) { - var got_exception = false; - - close_called = 0; - try { - cb(); - } catch (e) { - assert.equal(e.message, 'BAM'); - got_exception = true; - } - - assert.equal(close_called, 1); - assert.equal(got_exception, true); -} diff --git a/test/simple/test-fs-truncate-GH-6233.js b/test/simple/test-fs-truncate-GH-6233.js deleted file mode 100644 index 472afdcab..000000000 --- a/test/simple/test-fs-truncate-GH-6233.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -var filename = common.tmpDir + '/truncate-file.txt'; - -// Synchronous test. -(function() { - fs.writeFileSync(filename, '0123456789'); - assert.equal(fs.readFileSync(filename).toString(), '0123456789'); - fs.truncateSync(filename, 5); - assert.equal(fs.readFileSync(filename).toString(), '01234'); -})(); - -// Asynchronous test. -(function() { - fs.writeFileSync(filename, '0123456789'); - assert.equal(fs.readFileSync(filename).toString(), '0123456789'); - fs.truncate(filename, 5, common.mustCall(function(err) { - if (err) throw err; - assert.equal(fs.readFileSync(filename).toString(), '01234'); - })); -})(); diff --git a/test/simple/test-fs-truncate.js b/test/simple/test-fs-truncate.js deleted file mode 100644 index 09476b2ad..000000000 --- a/test/simple/test-fs-truncate.js +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var tmp = common.tmpDir; -var filename = path.resolve(tmp, 'truncate-file.txt'); -var data = new Buffer(1024 * 16); -data.fill('x'); - -var stat; - -// truncateSync -fs.writeFileSync(filename, data); -stat = fs.statSync(filename); -assert.equal(stat.size, 1024 * 16); - -fs.truncateSync(filename, 1024); -stat = fs.statSync(filename); -assert.equal(stat.size, 1024); - -fs.truncateSync(filename); -stat = fs.statSync(filename); -assert.equal(stat.size, 0); - -// ftruncateSync -fs.writeFileSync(filename, data); -var fd = fs.openSync(filename, 'r+'); - -stat = fs.statSync(filename); -assert.equal(stat.size, 1024 * 16); - -fs.ftruncateSync(fd, 1024); -stat = fs.statSync(filename); -assert.equal(stat.size, 1024); - -fs.ftruncateSync(fd); -stat = fs.statSync(filename); -assert.equal(stat.size, 0); - -fs.closeSync(fd); - -// async tests -var success = 0; -testTruncate(function(er) { - if (er) throw er; - success++; - testFtruncate(function(er) { - if (er) throw er; - success++; - }); -}); - -process.on('exit', function() { - assert.equal(success, 2); - console.log('ok'); -}); - -function testTruncate(cb) { - fs.writeFile(filename, data, function(er) { - if (er) return cb(er); - fs.stat(filename, function(er, stat) { - if (er) return cb(er); - assert.equal(stat.size, 1024 * 16); - - fs.truncate(filename, 1024, function(er) { - if (er) return cb(er); - fs.stat(filename, function(er, stat) { - if (er) return cb(er); - assert.equal(stat.size, 1024); - - fs.truncate(filename, function(er) { - if (er) return cb(er); - fs.stat(filename, function(er, stat) { - if (er) return cb(er); - assert.equal(stat.size, 0); - cb(); - }); - }); - }); - }); - }); - }); -} - - -function testFtruncate(cb) { - fs.writeFile(filename, data, function(er) { - if (er) return cb(er); - fs.stat(filename, function(er, stat) { - if (er) return cb(er); - assert.equal(stat.size, 1024 * 16); - - fs.open(filename, 'w', function(er, fd) { - if (er) return cb(er); - fs.ftruncate(fd, 1024, function(er) { - if (er) return cb(er); - fs.stat(filename, function(er, stat) { - if (er) return cb(er); - assert.equal(stat.size, 1024); - - fs.ftruncate(fd, function(er) { - if (er) return cb(er); - fs.stat(filename, function(er, stat) { - if (er) return cb(er); - assert.equal(stat.size, 0); - fs.close(fd, cb); - }); - }); - }); - }); - }); - }); - }); -} diff --git a/test/simple/test-fs-utimes.js b/test/simple/test-fs-utimes.js deleted file mode 100644 index eae80238b..000000000 --- a/test/simple/test-fs-utimes.js +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var fs = require('fs'); - -var is_windows = process.platform === 'win32'; - -var tests_ok = 0; -var tests_run = 0; - -function stat_resource(resource) { - if (typeof resource == 'string') { - return fs.statSync(resource); - } else { - // ensure mtime has been written to disk - fs.fsyncSync(resource); - return fs.fstatSync(resource); - } -} - -function check_mtime(resource, mtime) { - var mtime = fs._toUnixTimestamp(mtime); - var stats = stat_resource(resource); - var real_mtime = fs._toUnixTimestamp(stats.mtime); - // check up to single-second precision - // sub-second precision is OS and fs dependant - return Math.floor(mtime) == Math.floor(real_mtime); -} - -function expect_errno(syscall, resource, err, errno) { - if (err && (err.code === errno || err.code === 'ENOSYS')) { - tests_ok++; - } else { - console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); - } -} - -function expect_ok(syscall, resource, err, atime, mtime) { - if (!err && check_mtime(resource, mtime) || - err && err.code === 'ENOSYS') { - tests_ok++; - } else { - console.log('FAILED:', arguments.callee.name, util.inspect(arguments)); - } -} - -// the tests assume that __filename belongs to the user running the tests -// this should be a fairly safe assumption; testing against a temp file -// would be even better though (node doesn't have such functionality yet) -function runTest(atime, mtime, callback) { - - var fd, err; - // - // test synchronized code paths, these functions throw on failure - // - function syncTests() { - fs.utimesSync(__filename, atime, mtime); - expect_ok('utimesSync', __filename, undefined, atime, mtime); - tests_run++; - - // some systems don't have futimes - // if there's an error, it should be ENOSYS - try { - tests_run++; - fs.futimesSync(fd, atime, mtime); - expect_ok('futimesSync', fd, undefined, atime, mtime); - } catch (ex) { - expect_errno('futimesSync', fd, ex, 'ENOSYS'); - } - - var err; - err = undefined; - try { - fs.utimesSync('foobarbaz', atime, mtime); - } catch (ex) { - err = ex; - } - expect_errno('utimesSync', 'foobarbaz', err, 'ENOENT'); - tests_run++; - - err = undefined; - try { - fs.futimesSync(-1, atime, mtime); - } catch (ex) { - err = ex; - } - expect_errno('futimesSync', -1, err, 'EBADF'); - tests_run++; - } - - // - // test async code paths - // - fs.utimes(__filename, atime, mtime, function(err) { - expect_ok('utimes', __filename, err, atime, mtime); - - fs.utimes('foobarbaz', atime, mtime, function(err) { - expect_errno('utimes', 'foobarbaz', err, 'ENOENT'); - - // don't close this fd - if (is_windows) { - fd = fs.openSync(__filename, 'r+'); - } else { - fd = fs.openSync(__filename, 'r'); - } - - fs.futimes(fd, atime, mtime, function(err) { - expect_ok('futimes', fd, err, atime, mtime); - - fs.futimes(-1, atime, mtime, function(err) { - expect_errno('futimes', -1, err, 'EBADF'); - syncTests(); - callback(); - }); - tests_run++; - }); - tests_run++; - }); - tests_run++; - }); - tests_run++; -} - -var stats = fs.statSync(__filename); - -runTest(new Date('1982-09-10 13:37'), new Date('1982-09-10 13:37'), function() { - runTest(new Date(), new Date(), function() { - runTest(123456.789, 123456.789, function() { - runTest(stats.mtime, stats.mtime, function() { - // done - }); - }); - }); -}); - -process.on('exit', function() { - console.log('Tests run / ok:', tests_run, '/', tests_ok); - assert.equal(tests_ok, tests_run); -}); diff --git a/test/simple/test-fs-watch-recursive.js b/test/simple/test-fs-watch-recursive.js deleted file mode 100644 index e421ab022..000000000 --- a/test/simple/test-fs-watch-recursive.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -if (process.platform === 'darwin') { - var watchSeenOne = 0; - - var testDir = common.tmpDir; - - var filenameOne = 'watch.txt'; - var testsubdirName = 'testsubdir'; - var testsubdir = path.join(testDir, testsubdirName); - var relativePathOne = path.join('testsubdir', filenameOne); - var filepathOne = path.join(testsubdir, filenameOne); - - process.on('exit', function() { - assert.ok(watchSeenOne > 0); - }); - - function cleanup() { - try { fs.unlinkSync(filepathOne); } catch (e) { } - try { fs.rmdirSync(testsubdir); } catch (e) { } - }; - - try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} - - assert.doesNotThrow(function() { - var watcher = fs.watch(testDir, {recursive: true}); - watcher.on('change', function(event, filename) { - assert.ok('change' === event || 'rename' === event); - - // Ignore stale events generated by mkdir - if (filename === testsubdirName) - return; - - assert.equal(relativePathOne, filename); - - watcher.close(); - cleanup(); - ++watchSeenOne; - }); - }); - - setTimeout(function() { - fs.writeFileSync(filepathOne, 'world'); - }, 10); -} diff --git a/test/simple/test-fs-watch.js b/test/simple/test-fs-watch.js deleted file mode 100644 index 470736d59..000000000 --- a/test/simple/test-fs-watch.js +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var expectFilePath = process.platform === 'win32' || - process.platform === 'linux' || - process.platform === 'darwin'; - -var watchSeenOne = 0; -var watchSeenTwo = 0; -var watchSeenThree = 0; - -var testDir = common.tmpDir; - -var filenameOne = 'watch.txt'; -var filepathOne = path.join(testDir, filenameOne); - -var filenameTwo = 'hasOwnProperty'; -var filepathTwo = filenameTwo; -var filepathTwoAbs = path.join(testDir, filenameTwo); - -var filenameThree = 'newfile.txt'; -var testsubdir = path.join(testDir, 'testsubdir'); -var filepathThree = path.join(testsubdir, filenameThree); - - -process.on('exit', function() { - assert.ok(watchSeenOne > 0); - assert.ok(watchSeenTwo > 0); - assert.ok(watchSeenThree > 0); -}); - -// Clean up stale files (if any) from previous run. -try { fs.unlinkSync(filepathOne); } catch (e) { } -try { fs.unlinkSync(filepathTwoAbs); } catch (e) { } -try { fs.unlinkSync(filepathThree); } catch (e) { } -try { fs.rmdirSync(testsubdir); } catch (e) { } - -fs.writeFileSync(filepathOne, 'hello'); - -assert.doesNotThrow( - function() { - var watcher = fs.watch(filepathOne) - watcher.on('change', function(event, filename) { - assert.equal('change', event); - - if (expectFilePath) { - assert.equal('watch.txt', filename); - } - watcher.close(); - ++watchSeenOne; - }); - } -); - -setTimeout(function() { - fs.writeFileSync(filepathOne, 'world'); -}, 10); - - -process.chdir(testDir); - -fs.writeFileSync(filepathTwoAbs, 'howdy'); - -assert.doesNotThrow( - function() { - var watcher = fs.watch(filepathTwo, function(event, filename) { - assert.equal('change', event); - - if (expectFilePath) { - assert.equal('hasOwnProperty', filename); - } - watcher.close(); - ++watchSeenTwo; - }); - } -); - -setTimeout(function() { - fs.writeFileSync(filepathTwoAbs, 'pardner'); -}, 10); - -try { fs.unlinkSync(filepathThree); } catch (e) {} -try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} - -assert.doesNotThrow( - function() { - var watcher = fs.watch(testsubdir, function(event, filename) { - var renameEv = process.platform === 'sunos' ? 'change' : 'rename'; - assert.equal(renameEv, event); - if (expectFilePath) { - assert.equal('newfile.txt', filename); - } else { - assert.equal(null, filename); - } - watcher.close(); - ++watchSeenThree; - }); - } -); - -setTimeout(function() { - var fd = fs.openSync(filepathThree, 'w'); - fs.closeSync(fd); -}, 10); - -// https://github.com/joyent/node/issues/2293 - non-persistent watcher should -// not block the event loop -fs.watch(__filename, {persistent: false}, function() { - assert(0); -}); - -// whitebox test to ensure that wrapped FSEvent is safe -// https://github.com/joyent/node/issues/6690 -var oldhandle; -assert.throws(function() { - var w = fs.watch(__filename, function(event, filename) { }); - oldhandle = w._handle; - w._handle = { close: w._handle.close }; - w.close(); -}, TypeError); -oldhandle.close(); // clean up - -assert.throws(function() { - var w = fs.watchFile(__filename, {persistent:false}, function(){}); - oldhandle = w._handle; - w._handle = { stop: w._handle.stop }; - w.stop(); -}, TypeError); -oldhandle.stop(); // clean up diff --git a/test/simple/test-fs-write-buffer.js b/test/simple/test-fs-write-buffer.js deleted file mode 100644 index 46013bd87..000000000 --- a/test/simple/test-fs-write-buffer.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'), - Buffer = require('buffer').Buffer, - fs = require('fs'), - filename = path.join(common.tmpDir, 'write.txt'), - expected = new Buffer('hello'), - openCalled = 0, - writeCalled = 0; - - -fs.open(filename, 'w', 0644, function(err, fd) { - openCalled++; - if (err) throw err; - - fs.write(fd, expected, 0, expected.length, null, function(err, written) { - writeCalled++; - if (err) throw err; - - assert.equal(expected.length, written); - fs.closeSync(fd); - - var found = fs.readFileSync(filename, 'utf8'); - assert.deepEqual(expected.toString(), found); - fs.unlinkSync(filename); - }); -}); - -process.on('exit', function() { - assert.equal(1, openCalled); - assert.equal(1, writeCalled); -}); - diff --git a/test/simple/test-fs-write-file-buffer.js b/test/simple/test-fs-write-file-buffer.js deleted file mode 100644 index dfe7cf5f3..000000000 --- a/test/simple/test-fs-write-file-buffer.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var join = require('path').join; -var util = require('util'); -var fs = require('fs'); - -var data = [ - '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', - 'Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/', - '2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e', - 'Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAQABADASIAAhEBAxEB/8QA', - 'HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF', - 'BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK', - 'FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1', - 'dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG', - 'x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEB', - 'AQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC', - 'AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRom', - 'JygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE', - 'hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU', - '1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDhfBUFl/wk', - 'OmPqKJJZw3aiZFBw4z93jnkkc9u9dj8XLfSI/EBt7DTo7ea2Ox5YXVo5FC7g', - 'Tjq24nJPXNVtO0KATRvNHCIg3zoWJWQHqp+o4pun+EtJ0zxBq8mnLJa2d1L5', - '0NvnKRjJBUE5PAx3NYxxUY0pRtvYHSc5Ka2X9d7H/9k=']; - -data = data.join('\n'); - -var buf = new Buffer(data, 'base64'); -fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); - -util.log('Done!'); diff --git a/test/simple/test-fs-write-file-sync.js b/test/simple/test-fs-write-file-sync.js deleted file mode 100644 index 3e723425a..000000000 --- a/test/simple/test-fs-write-file-sync.js +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var isWindows = process.platform === 'win32'; -var openCount = 0; -var mode; -var content; - -// Need to hijack fs.open/close to make sure that things -// get closed once they're opened. -fs._openSync = fs.openSync; -fs.openSync = openSync; -fs._closeSync = fs.closeSync; -fs.closeSync = closeSync; - -// Reset the umask for testing -var mask = process.umask(0000); - -// On Windows chmod is only able to manipulate read-only bit. Test if creating -// the file in read-only mode works. -if (isWindows) { - mode = 0444; -} else { - mode = 0755; -} - -// Test writeFileSync -var file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); -removeFile(file1); - -fs.writeFileSync(file1, '123', {mode: mode}); - -content = fs.readFileSync(file1, {encoding: 'utf8'}); -assert.equal('123', content); - -assert.equal(mode, fs.statSync(file1).mode & 0777); - -removeFile(file1); - -// Test appendFileSync -var file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); -removeFile(file2); - -fs.appendFileSync(file2, 'abc', {mode: mode}); - -content = fs.readFileSync(file2, {encoding: 'utf8'}); -assert.equal('abc', content); - -assert.equal(mode, fs.statSync(file2).mode & mode); - -removeFile(file2); - -// Verify that all opened files were closed. -assert.equal(0, openCount); - -// Removes a file if it exists. -function removeFile(file) { - try { - if (isWindows) - fs.chmodSync(file, 0666); - fs.unlinkSync(file); - } catch (err) { - if (err && err.code !== 'ENOENT') - throw err; - } -} - -function openSync() { - openCount++; - return fs._openSync.apply(fs, arguments); -} - -function closeSync() { - openCount--; - return fs._closeSync.apply(fs, arguments); -} diff --git a/test/simple/test-fs-write-file.js b/test/simple/test-fs-write-file.js deleted file mode 100644 index b70ea444c..000000000 --- a/test/simple/test-fs-write-file.js +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var join = require('path').join; - -var filename = join(common.tmpDir, 'test.txt'); - -common.error('writing to ' + filename); - -var n = 220; -var s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' + - '广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' + - '南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' + - '前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + - '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + - '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + - '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; - -var ncallbacks = 0; - -fs.writeFile(filename, s, function(e) { - if (e) throw e; - - ncallbacks++; - common.error('file written'); - - fs.readFile(filename, function(e, buffer) { - if (e) throw e; - common.error('file read'); - ncallbacks++; - assert.equal(Buffer.byteLength(s), buffer.length); - }); -}); - -// test that writeFile accepts buffers -var filename2 = join(common.tmpDir, 'test2.txt'); -var buf = new Buffer(s, 'utf8'); -common.error('writing to ' + filename2); - -fs.writeFile(filename2, buf, function(e) { - if (e) throw e; - - ncallbacks++; - common.error('file2 written'); - - fs.readFile(filename2, function(e, buffer) { - if (e) throw e; - common.error('file2 read'); - ncallbacks++; - assert.equal(buf.length, buffer.length); - }); -}); - -// test that writeFile accepts numbers. -var filename3 = join(common.tmpDir, 'test3.txt'); -common.error('writing to ' + filename3); - -var m = 0600; -fs.writeFile(filename3, n, { mode: m }, function(e) { - if (e) throw e; - - // windows permissions aren't unix - if (process.platform !== 'win32') { - var st = fs.statSync(filename3); - assert.equal(st.mode & 0700, m); - } - - ncallbacks++; - common.error('file3 written'); - - fs.readFile(filename3, function(e, buffer) { - if (e) throw e; - common.error('file3 read'); - ncallbacks++; - assert.equal(Buffer.byteLength('' + n), buffer.length); - }); -}); - - -process.on('exit', function() { - common.error('done'); - assert.equal(6, ncallbacks); - - fs.unlinkSync(filename); - fs.unlinkSync(filename2); - fs.unlinkSync(filename3); -}); diff --git a/test/simple/test-fs-write-stream-change-open.js b/test/simple/test-fs-write-stream-change-open.js deleted file mode 100644 index d025e8da3..000000000 --- a/test/simple/test-fs-write-stream-change-open.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'), - fs = require('fs'); - -var file = path.join(common.tmpDir, 'write.txt'); - -var stream = fs.WriteStream(file), - _fs_close = fs.close, - _fs_open = fs.open; - -// change the fs.open with an identical function after the WriteStream -// has pushed it onto its internal action queue, but before it's -// returned. This simulates AOP-style extension of the fs lib. -fs.open = function() { - return _fs_open.apply(fs, arguments); -}; - -fs.close = function(fd) { - assert.ok(fd, 'fs.close must not be called with an undefined fd.'); - fs.close = _fs_close; - fs.open = _fs_open; -} - -stream.write('foo'); -stream.end(); - -process.on('exit', function() { - assert.equal(fs.open, _fs_open); -}); diff --git a/test/simple/test-fs-write-stream-end.js b/test/simple/test-fs-write-stream-end.js deleted file mode 100644 index 7bbc5d68e..000000000 --- a/test/simple/test-fs-write-stream-end.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -(function() { - var file = path.join(common.tmpDir, 'write-end-test0.txt'); - var stream = fs.createWriteStream(file); - stream.end(); - stream.on('close', common.mustCall(function() { })); -})(); - -(function() { - var file = path.join(common.tmpDir, 'write-end-test1.txt'); - var stream = fs.createWriteStream(file); - stream.end('a\n', 'utf8'); - stream.on('close', common.mustCall(function() { - var content = fs.readFileSync(file, 'utf8'); - assert.equal(content, 'a\n'); - })); -})(); diff --git a/test/simple/test-fs-write-stream-err.js b/test/simple/test-fs-write-stream-err.js deleted file mode 100644 index 53ef4e34e..000000000 --- a/test/simple/test-fs-write-stream-err.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); - -var stream = fs.createWriteStream(common.tmpDir + '/out', { - highWaterMark: 10 -}); -var err = new Error('BAM'); - -var write = fs.write; -var writeCalls = 0; -fs.write = function() { - switch (writeCalls++) { - case 0: - console.error('first write'); - // first time is ok. - return write.apply(fs, arguments); - case 1: - // then it breaks - console.error('second write'); - var cb = arguments[arguments.length - 1]; - return process.nextTick(function() { - cb(err); - }); - default: - // and should not be called again! - throw new Error('BOOM!'); - } -}; - -fs.close = common.mustCall(function(fd_, cb) { - console.error('fs.close', fd_, stream.fd); - assert.equal(fd_, stream.fd); - process.nextTick(cb); -}); - -stream.on('error', common.mustCall(function(err_) { - console.error('error handler'); - assert.equal(stream.fd, null); - assert.equal(err_, err); -})); - - -stream.write(new Buffer(256), function() { - console.error('first cb'); - stream.write(new Buffer(256), common.mustCall(function(err_) { - console.error('second cb'); - assert.equal(err_, err); - })); -}); diff --git a/test/simple/test-fs-write-stream.js b/test/simple/test-fs-write-stream.js deleted file mode 100644 index da75e26f8..000000000 --- a/test/simple/test-fs-write-stream.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'), - fs = require('fs'); - -var file = path.join(common.tmpDir, 'write.txt'); - -(function() { - var stream = fs.WriteStream(file), - _fs_close = fs.close; - - fs.close = function(fd) { - assert.ok(fd, 'fs.close must not be called without an undefined fd.'); - fs.close = _fs_close; - } - stream.destroy(); -})(); - -(function() { - var stream = fs.createWriteStream(file); - - stream.on('drain', function() { - assert.fail('\'drain\' event must not be emitted before ' + - 'stream.write() has been called at least once.'); - }); - stream.destroy(); -})(); - diff --git a/test/simple/test-fs-write-sync.js b/test/simple/test-fs-write-sync.js deleted file mode 100644 index c3dbfe3ba..000000000 --- a/test/simple/test-fs-write-sync.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); -var fn = path.join(common.tmpDir, 'write.txt'); - - -var foo = 'foo'; -var fd = fs.openSync(fn, 'w'); - -var written = fs.writeSync(fd, ''); -assert.strictEqual(0, written); - -fs.writeSync(fd, foo); - -var bar = 'bár'; -written = fs.writeSync(fd, new Buffer(bar), 0, Buffer.byteLength(bar)); -assert.ok(written > 3); -fs.closeSync(fd); - -assert.equal(fs.readFileSync(fn), 'foobár'); diff --git a/test/simple/test-fs-write.js b/test/simple/test-fs-write.js deleted file mode 100644 index 3d7a357a9..000000000 --- a/test/simple/test-fs-write.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var Buffer = require('buffer').Buffer; -var fs = require('fs'); -var fn = path.join(common.tmpDir, 'write.txt'); -var fn2 = path.join(common.tmpDir, 'write2.txt'); -var expected = 'ümlaut.'; -var constants = require('constants'); -var found, found2; - -fs.open(fn, 'w', 0644, function(err, fd) { - if (err) throw err; - console.log('open done'); - fs.write(fd, '', 0, 'utf8', function(err, written) { - assert.equal(0, written); - }); - fs.write(fd, expected, 0, 'utf8', function(err, written) { - console.log('write done'); - if (err) throw err; - assert.equal(Buffer.byteLength(expected), written); - fs.closeSync(fd); - found = fs.readFileSync(fn, 'utf8'); - console.log('expected: "%s"', expected); - console.log('found: "%s"', found); - fs.unlinkSync(fn); - }); -}); - - -fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0644, - function(err, fd) { - if (err) throw err; - console.log('open done'); - fs.write(fd, '', 0, 'utf8', function(err, written) { - assert.equal(0, written); - }); - fs.write(fd, expected, 0, 'utf8', function(err, written) { - console.log('write done'); - if (err) throw err; - assert.equal(Buffer.byteLength(expected), written); - fs.closeSync(fd); - found2 = fs.readFileSync(fn2, 'utf8'); - console.log('expected: "%s"', expected); - console.log('found: "%s"', found2); - fs.unlinkSync(fn2); - }); - }); - - -process.on('exit', function() { - assert.equal(expected, found); - assert.equal(expected, found2); -}); - diff --git a/test/simple/test-global.js b/test/simple/test-global.js deleted file mode 100644 index 4cc9799ba..000000000 --- a/test/simple/test-global.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -common.globalCheck = false; - -baseFoo = 'foo'; -global.baseBar = 'bar'; - -assert.equal('foo', global.baseFoo, 'x -> global.x in base level not working'); - -assert.equal('bar', baseBar, 'global.x -> x in base level not working'); - -var module = require('../fixtures/global/plain'), - fooBar = module.fooBar; - -assert.equal('foo', fooBar.foo, 'x -> global.x in sub level not working'); - -assert.equal('bar', fooBar.bar, 'global.x -> x in sub level not working'); diff --git a/test/simple/test-handle-wrap-close-abort.js b/test/simple/test-handle-wrap-close-abort.js deleted file mode 100644 index 287c38b23..000000000 --- a/test/simple/test-handle-wrap-close-abort.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -process.on('uncaughtException', function() { }); - -setTimeout(function() { - process.nextTick(function() { - var c = setInterval(function() { - clearInterval(c); - throw new Error('setInterval'); - }); - }); - setTimeout(function() { - throw new Error('setTimeout'); - }); -}); diff --git a/test/simple/test-http-1.0-keep-alive.js b/test/simple/test-http-1.0-keep-alive.js deleted file mode 100644 index 851409d28..000000000 --- a/test/simple/test-http-1.0-keep-alive.js +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -// Check that our HTTP server correctly handles HTTP/1.0 keep-alive requests. -check([{ - name: 'keep-alive, no TE header', - requests: [{ - expectClose: true, - data: 'POST / HTTP/1.0\r\n' + - 'Connection: keep-alive\r\n' + - '\r\n' - }, { - expectClose: true, - data: 'POST / HTTP/1.0\r\n' + - 'Connection: keep-alive\r\n' + - '\r\n' - }], - responses: [{ - headers: {'Connection': 'keep-alive'}, - chunks: ['OK'] - }, { - chunks: [] - }] -}, { - name: 'keep-alive, with TE: chunked', - requests: [{ - expectClose: false, - data: 'POST / HTTP/1.0\r\n' + - 'Connection: keep-alive\r\n' + - 'TE: chunked\r\n' + - '\r\n' - }, { - expectClose: true, - data: 'POST / HTTP/1.0\r\n' + - '\r\n' - }], - responses: [{ - headers: {'Connection': 'keep-alive'}, - chunks: ['OK'] - }, { - chunks: [] - }] -}, { - name: 'keep-alive, with Transfer-Encoding: chunked', - requests: [{ - expectClose: false, - data: 'POST / HTTP/1.0\r\n' + - 'Connection: keep-alive\r\n' + - '\r\n' - }, { - expectClose: true, - data: 'POST / HTTP/1.0\r\n' + - '\r\n' - }], - responses: [{ - headers: {'Connection': 'keep-alive', - 'Transfer-Encoding': 'chunked'}, - chunks: ['OK'] - }, { - chunks: [] - }] -}, { - name: 'keep-alive, with Content-Length', - requests: [{ - expectClose: false, - data: 'POST / HTTP/1.0\r\n' + - 'Connection: keep-alive\r\n' + - '\r\n' - }, { - expectClose: true, - data: 'POST / HTTP/1.0\r\n' + - '\r\n' - }], - responses: [{ - headers: {'Connection': 'keep-alive', - 'Content-Length': '2'}, - chunks: ['OK'] - }, { - chunks: [] - }] -}]); - -function check(tests) { - var test = tests[0]; - if (test) http.createServer(server).listen(common.PORT, '127.0.0.1', client); - var current = 0; - - function next() { - check(tests.slice(1)); - } - - function server(req, res) { - if (current + 1 === test.responses.length) this.close(); - var ctx = test.responses[current]; - console.error('< SERVER SENDING RESPONSE', ctx); - res.writeHead(200, ctx.headers); - ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk) }); - res.end(ctx.chunks[ctx.chunks.length - 1]); - } - - function client() { - if (current === test.requests.length) return next(); - var conn = net.createConnection(common.PORT, '127.0.0.1', connected); - - function connected() { - var ctx = test.requests[current]; - console.error(' > CLIENT SENDING REQUEST', ctx); - conn.setEncoding('utf8'); - conn.write(ctx.data); - - function onclose() { - console.error(' > CLIENT CLOSE'); - if (!ctx.expectClose) throw new Error('unexpected close'); - client(); - } - conn.on('close', onclose); - - function ondata(s) { - console.error(' > CLIENT ONDATA %j %j', s.length, s.toString()); - current++; - if (ctx.expectClose) return; - conn.removeListener('close', onclose); - conn.removeListener('data', ondata);; - connected(); - } - conn.on('data', ondata); - } - } -} diff --git a/test/simple/test-http-1.0.js b/test/simple/test-http-1.0.js deleted file mode 100644 index f5f3aef0a..000000000 --- a/test/simple/test-http-1.0.js +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); - -var body = 'hello world\n'; - -var common_port = common.PORT; - -function test(handler, request_generator, response_validator) { - var port = common_port++; - var server = http.createServer(handler); - - var client_got_eof = false; - var server_response = { - data: '', - chunks: [] - }; - - function cleanup() { - server.close(); - response_validator(server_response, client_got_eof, true); - } - var timer = setTimeout(cleanup, 1000); - process.on('exit', cleanup); - - server.listen(port); - server.on('listening', function() { - var c = net.createConnection(port); - - c.setEncoding('utf8'); - - c.on('connect', function() { - c.write(request_generator()); - }); - - c.on('data', function(chunk) { - server_response.data += chunk; - server_response.chunks.push(chunk); - }); - - c.on('end', function() { - client_got_eof = true; - c.end(); - server.close(); - clearTimeout(timer); - process.removeListener('exit', cleanup); - response_validator(server_response, client_got_eof, false); - }); - }); -} - -(function() { - function handler(req, res) { - assert.equal('1.0', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(0, req.httpVersionMinor); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end(body); - } - - function request_generator() { - return 'GET / HTTP/1.0\r\n\r\n'; - } - - function response_validator(server_response, client_got_eof, timed_out) { - var m = server_response.data.split('\r\n\r\n'); - assert.equal(m[1], body); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); - } - - test(handler, request_generator, response_validator); -})(); - -// -// Don't send HTTP/1.1 status lines to HTTP/1.0 clients. -// -// https://github.com/joyent/node/issues/1234 -// -(function() { - function handler(req, res) { - assert.equal('1.0', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(0, req.httpVersionMinor); - res.sendDate = false; - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('Hello, '); res._send(''); - res.write('world!'); res._send(''); - res.end(); - } - - function request_generator() { - return ('GET / HTTP/1.0\r\n' + - 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + - 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + - 'Host: 127.0.0.1:1337\r\n' + - 'Accept: */*\r\n' + - '\r\n'); - } - - function response_validator(server_response, client_got_eof, timed_out) { - var expected_response = ('HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Connection: close\r\n' + - '\r\n' + - 'Hello, world!'); - - assert.equal(expected_response, server_response.data); - assert.equal(1, server_response.chunks.length); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); - } - - test(handler, request_generator, response_validator); -})(); - -(function() { - function handler(req, res) { - assert.equal('1.1', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(1, req.httpVersionMinor); - res.sendDate = false; - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('Hello, '); res._send(''); - res.write('world!'); res._send(''); - res.end(); - } - - function request_generator() { - return ('GET / HTTP/1.1\r\n' + - 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + - 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + - 'Connection: close\r\n' + - 'Host: 127.0.0.1:1337\r\n' + - 'Accept: */*\r\n' + - '\r\n'); - } - - function response_validator(server_response, client_got_eof, timed_out) { - var expected_response = ('HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Connection: close\r\n' + - 'Transfer-Encoding: chunked\r\n' + - '\r\n' + - '7\r\n' + - 'Hello, \r\n' + - '6\r\n' + - 'world!\r\n' + - '0\r\n' + - '\r\n'); - - assert.equal(expected_response, server_response.data); - assert.equal(1, server_response.chunks.length); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); - } - - test(handler, request_generator, response_validator); -})(); diff --git a/test/simple/test-http-304.js b/test/simple/test-http-304.js deleted file mode 100644 index fcef21aee..000000000 --- a/test/simple/test-http-304.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var childProcess = require('child_process'); - -var s = http.createServer(function(request, response) { - response.writeHead(304); - response.end(); -}); - -s.listen(common.PORT, function() { - childProcess.exec('curl -i http://127.0.0.1:' + common.PORT + '/', - function(err, stdout, stderr) { - if (err) throw err; - s.close(); - common.error('curled response correctly'); - common.error(common.inspect(stdout)); - }); -}); - -console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); diff --git a/test/simple/test-http-abort-before-end.js b/test/simple/test-http-abort-before-end.js deleted file mode 100644 index 11e424fbe..000000000 --- a/test/simple/test-http-abort-before-end.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); - -var server = http.createServer(function(req, res) { - assert(false); // should not be called -}); - -server.listen(common.PORT, function() { - var req = http.request({method: 'GET', host: '127.0.0.1', port: common.PORT}); - - req.on('error', function(ex) { - // https://github.com/joyent/node/issues/1399#issuecomment-2597359 - // abort() should emit an Error, not the net.Socket object - assert(ex instanceof Error); - }); - - req.abort(); - req.end(); - - server.close(); -}); diff --git a/test/simple/test-http-abort-client.js b/test/simple/test-http-abort-client.js deleted file mode 100644 index f15238af1..000000000 --- a/test/simple/test-http-abort-client.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); - -var server = http.Server(function(req, res) { - console.log('Server accepted request.'); - res.writeHead(200); - res.write('Part of my res.'); - - res.destroy(); -}); - -var responseClose = false; - -server.listen(common.PORT, function() { - var client = http.get({ - port: common.PORT, - headers: { connection: 'keep-alive' } - - }, function(res) { - server.close(); - - console.log('Got res: ' + res.statusCode); - console.dir(res.headers); - - res.on('data', function(chunk) { - console.log('Read ' + chunk.length + ' bytes'); - console.log(' chunk=%j', chunk.toString()); - }); - - res.on('end', function() { - console.log('Response ended.'); - }); - - res.on('aborted', function() { - console.log('Response aborted.'); - }); - - res.socket.on('close', function() { - console.log('socket closed, but not res'); - }) - - // it would be nice if this worked: - res.on('close', function() { - console.log('Response aborted'); - responseClose = true; - }); - }); -}); - - -process.on('exit', function() { - assert.ok(responseClose); -}); diff --git a/test/simple/test-http-abort-queued.js b/test/simple/test-http-abort-queued.js deleted file mode 100644 index d3ec5a14d..000000000 --- a/test/simple/test-http-abort-queued.js +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'), - http = require('http'); - -var complete; - -var server = http.createServer(function (req, res) { - // We should not see the queued /thatotherone request within the server - // as it should be aborted before it is sent. - assert.equal(req.url, '/'); - - res.writeHead(200); - res.write('foo'); - - complete = complete || function () { - res.end(); - }; -}); - - -server.listen(0, function () { - console.log('listen', server.address().port); - - var agent = new http.Agent({maxSockets: 1}); - assert.equal(Object.keys(agent.sockets).length, 0); - - var options = { - hostname: 'localhost', - port: server.address().port, - method: 'GET', - path: '/', - agent: agent - }; - - var req1 = http.request(options); - req1.on('response', function(res1) { - assert.equal(Object.keys(agent.sockets).length, 1); - assert.equal(Object.keys(agent.requests).length, 0); - - var req2 = http.request({ - method: 'GET', - host: 'localhost', - port: server.address().port, - path: '/thatotherone', - agent: agent - }); - assert.equal(Object.keys(agent.sockets).length, 1); - assert.equal(Object.keys(agent.requests).length, 1); - - req2.on('error', function(err) { - // This is expected in response to our explicit abort call - assert.equal(err.code, 'ECONNRESET'); - }); - - req2.end(); - req2.abort(); - - assert.equal(Object.keys(agent.sockets).length, 1); - assert.equal(Object.keys(agent.requests).length, 1); - - console.log('Got res: ' + res1.statusCode); - console.dir(res1.headers); - - res1.on('data', function(chunk) { - console.log('Read ' + chunk.length + ' bytes'); - console.log(' chunk=%j', chunk.toString()); - complete(); - }); - - res1.on('end', function() { - console.log('Response ended.'); - - setTimeout(function() { - assert.equal(Object.keys(agent.sockets).length, 0); - assert.equal(Object.keys(agent.requests).length, 0); - - server.close(); - }, 100); - }); - }); - - req1.end(); -}); diff --git a/test/simple/test-http-after-connect.js b/test/simple/test-http-after-connect.js deleted file mode 100644 index 08b2c14a6..000000000 --- a/test/simple/test-http-after-connect.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var serverConnected = false; -var serverRequests = 0; -var clientResponses = 0; - -var server = http.createServer(function(req, res) { - common.debug('Server got GET request'); - req.resume(); - ++serverRequests; - res.writeHead(200); - res.write(''); - setTimeout(function() { - res.end(req.url); - }, 50); -}); -server.on('connect', function(req, socket, firstBodyChunk) { - common.debug('Server got CONNECT request'); - serverConnected = true; - socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); - socket.resume(); - socket.on('end', function() { - socket.end(); - }); -}); -server.listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - method: 'CONNECT', - path: 'google.com:80' - }); - req.on('connect', function(res, socket, firstBodyChunk) { - common.debug('Client got CONNECT response'); - socket.end(); - socket.on('end', function() { - doRequest(0); - doRequest(1); - }); - socket.resume(); - }); - req.end(); -}); - -function doRequest(i) { - var req = http.get({ - port: common.PORT, - path: '/request' + i - }, function(res) { - common.debug('Client got GET response'); - var data = ''; - res.setEncoding('utf8'); - res.on('data', function(chunk) { - data += chunk; - }); - res.on('end', function() { - assert.equal(data, '/request' + i); - ++clientResponses; - if (clientResponses === 2) { - server.close(); - } - }); - }); -} - -process.on('exit', function() { - assert(serverConnected); - assert.equal(serverRequests, 2); - assert.equal(clientResponses, 2); -}); diff --git a/test/simple/test-http-agent-destroyed-socket.js b/test/simple/test-http-agent-destroyed-socket.js deleted file mode 100644 index be90bc677..000000000 --- a/test/simple/test-http-agent-destroyed-socket.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World\n'); -}).listen(common.PORT); - -var agent = new http.Agent({maxSockets: 1}); - -agent.on('free', function(socket, host, port) { - console.log('freeing socket. destroyed? ', socket.destroyed); -}); - -var requestOptions = { - agent: agent, - host: 'localhost', - port: common.PORT, - path: '/' -}; - -var request1 = http.get(requestOptions, function(response) { - // assert request2 is queued in the agent - var key = agent.getName(requestOptions); - assert(agent.requests[key].length === 1); - console.log('got response1'); - request1.socket.on('close', function() { - console.log('request1 socket closed'); - }); - response.pipe(process.stdout); - response.on('end', function() { - console.log('response1 done'); - ///////////////////////////////// - // - // THE IMPORTANT PART - // - // It is possible for the socket to get destroyed and other work - // to run before the 'close' event fires because it happens on - // nextTick. This example is contrived because it destroys the - // socket manually at just the right time, but at Voxer we have - // seen cases where the socket is destroyed by non-user code - // then handed out again by an agent *before* the 'close' event - // is triggered. - request1.socket.destroy(); - - response.once('close', function() { - // assert request2 was removed from the queue - assert(!agent.requests[key]); - console.log("waiting for request2.onSocket's nextTick"); - process.nextTick(function() { - // assert that the same socket was not assigned to request2, - // since it was destroyed. - assert(request1.socket !== request2.socket); - assert(!request2.socket.destroyed, 'the socket is destroyed'); - }); - }); - }); -}); - -var request2 = http.get(requestOptions, function(response) { - assert(!request2.socket.destroyed); - assert(request1.socket.destroyed); - // assert not reusing the same socket, since it was destroyed. - assert(request1.socket !== request2.socket); - console.log('got response2'); - var gotClose = false; - var gotResponseEnd = false; - request2.socket.on('close', function() { - console.log('request2 socket closed'); - gotClose = true; - done(); - }); - response.pipe(process.stdout); - response.on('end', function() { - console.log('response2 done'); - gotResponseEnd = true; - done(); - }); - - function done() { - if (gotResponseEnd && gotClose) - server.close(); - } -}); diff --git a/test/simple/test-http-agent-false.js b/test/simple/test-http-agent-false.js deleted file mode 100644 index d897ab603..000000000 --- a/test/simple/test-http-agent-false.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -// sending `agent: false` when `port: null` is also passed in (i.e. the result of -// a `url.parse()` call with the default port used, 80 or 443), should not result -// in an assertion error... -var opts = { - host: '127.0.0.1', - port: null, - path: '/', - method: 'GET', - agent: false -}; - -var good = false; -process.on('exit', function() { - assert(good, 'expected either an "error" or "response" event'); -}); - -// we just want an "error" (no local HTTP server on port 80) or "response" -// to happen (user happens ot have HTTP server running on port 80). As long as the -// process doesn't crash from a C++ assertion then we're good. -var req = http.request(opts); -req.on('response', function(res) { - good = true; -}); -req.on('error', function(err) { - // an "error" event is ok, don't crash the process - good = true; -}); -req.end(); diff --git a/test/simple/test-http-agent-keepalive.js b/test/simple/test-http-agent-keepalive.js deleted file mode 100644 index f56027a72..000000000 --- a/test/simple/test-http-agent-keepalive.js +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var Agent = require('_http_agent').Agent; -var EventEmitter = require('events').EventEmitter; - -var agent = new Agent({ - keepAlive: true, - keepAliveMsecs: 1000, - maxSockets: 5, - maxFreeSockets: 5 -}); - -var server = http.createServer(function (req, res) { - if (req.url === '/error') { - res.destroy(); - return; - } else if (req.url === '/remote_close') { - // cache the socket, close it after 100ms - var socket = res.connection; - setTimeout(function () { - socket.end(); - }, 100); - } - res.end('hello world'); -}); - -function get(path, callback) { - return http.get({ - host: 'localhost', - port: common.PORT, - agent: agent, - path: path - }, callback); -} - -var name = 'localhost:' + common.PORT + '::'; - -function checkDataAndSockets(body) { - assert.equal(body.toString(), 'hello world'); - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); -} - -function second() { - // request second, use the same socket - get('/second', function (res) { - assert.equal(res.statusCode, 200); - res.on('data', checkDataAndSockets); - res.on('end', function () { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name].length, 1); - remoteClose(); - }); - }); - }); -} - -function remoteClose() { - // mock remote server close the socket - get('/remote_close', function (res) { - assert.deepEqual(res.statusCode, 200); - res.on('data', checkDataAndSockets); - res.on('end', function () { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name].length, 1); - // waitting remote server close the socket - setTimeout(function () { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name], undefined, - 'freeSockets is not empty'); - remoteError(); - }, 200); - }); - }); - }); -} - -function remoteError() { - // remove server will destroy ths socket - var req = get('/error', function (res) { - throw new Error('should not call this function'); - }); - req.on('error', function (err) { - assert.ok(err); - assert.equal(err.message, 'socket hang up'); - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); - // Wait socket 'close' event emit - setTimeout(function () { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name], undefined); - done(); - }, 1); - }); -} - -function done() { - console.log('http keepalive agent test success.'); - process.exit(0); -} - -server.listen(common.PORT, function() { - // request first, and keep alive - get('/first', function (res) { - assert.equal(res.statusCode, 200); - res.on('data', checkDataAndSockets); - res.on('end', function () { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { - assert.equal(agent.sockets[name], undefined); - assert.equal(agent.freeSockets[name].length, 1); - second(); - }); - }); - }); -}); diff --git a/test/simple/test-http-agent-no-protocol.js b/test/simple/test-http-agent-no-protocol.js deleted file mode 100644 index fa224c5a7..000000000 --- a/test/simple/test-http-agent-no-protocol.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -var request = 0; -var response = 0; -process.on('exit', function() { - assert.equal(1, request, 'http server "request" callback was not called'); - assert.equal(1, response, 'http client "response" callback was not called'); -}); - -var server = http.createServer(function(req, res) { - res.end(); - request++; -}).listen(common.PORT, '127.0.0.1', function() { - var opts = url.parse('http://127.0.0.1:' + common.PORT + '/'); - - // remove the `protocol` field… the `http` module should fall back - // to "http:", as defined by the global, default `http.Agent` instance. - opts.agent = new http.Agent(); - opts.agent.protocol = null; - - http.get(opts, function (res) { - response++; - res.resume(); - server.close(); - }); -}); diff --git a/test/simple/test-http-agent-null.js b/test/simple/test-http-agent-null.js deleted file mode 100644 index 8ae71d508..000000000 --- a/test/simple/test-http-agent-null.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var request = 0; -var response = 0; -process.on('exit', function() { - assert.equal(request, 1, 'http server "request" callback was not called'); - assert.equal(response, 1, 'http request "response" callback was not called'); -}); - -var server = http.createServer(function(req, res) { - request++; - res.end(); -}).listen(function() { - var options = { - agent: null, - port: this.address().port - }; - http.get(options, function(res) { - response++; - res.resume(); - server.close(); - }); -}); diff --git a/test/simple/test-http-agent.js b/test/simple/test-http-agent.js deleted file mode 100644 index fc66dc49f..000000000 --- a/test/simple/test-http-agent.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.Server(function(req, res) { - res.writeHead(200); - res.end('hello world\n'); -}); - -var responses = 0; -var N = 10; -var M = 10; - -server.listen(common.PORT, function() { - for (var i = 0; i < N; i++) { - setTimeout(function() { - for (var j = 0; j < M; j++) { - http.get({ port: common.PORT, path: '/' }, function(res) { - console.log('%d %d', responses, res.statusCode); - if (++responses == N * M) { - console.error('Received all responses, closing server'); - server.close(); - } - res.resume(); - }).on('error', function(e) { - console.log('Error!', e); - process.exit(1); - }); - } - }, i); - } -}); - - -process.on('exit', function() { - assert.equal(N * M, responses); -}); diff --git a/test/simple/test-http-allow-req-after-204-res.js b/test/simple/test-http-allow-req-after-204-res.js deleted file mode 100644 index 225ff299e..000000000 --- a/test/simple/test-http-allow-req-after-204-res.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); - -// first 204 or 304 works, subsequent anything fails -var codes = [204, 200]; - -// Methods don't really matter, but we put in something realistic. -var methods = ['DELETE', 'DELETE']; - -var server = http.createServer(function(req, res) { - var code = codes.shift(); - assert.equal('number', typeof code); - assert.ok(code > 0); - console.error('writing %d response', code); - res.writeHead(code, {}); - res.end(); -}); - -function nextRequest() { - var method = methods.shift(); - console.error('writing request: %s', method); - - var request = http.request({ - port: common.PORT, - method: method, - path: '/' - }, function(response) { - response.on('end', function() { - if (methods.length == 0) { - console.error('close server'); - server.close(); - } else { - // throws error: - nextRequest(); - // works just fine: - //process.nextTick(nextRequest); - } - }); - response.resume(); - }); - request.end(); -} - -server.listen(common.PORT, nextRequest); diff --git a/test/simple/test-http-bind-twice.js b/test/simple/test-http-bind-twice.js deleted file mode 100644 index 59d69efaa..000000000 --- a/test/simple/test-http-bind-twice.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var gotError = false; - -process.on('exit', function() { - assert(gotError); -}); - -function dontCall() { - assert(false); -} - -var server1 = http.createServer(dontCall); -server1.listen(common.PORT, '127.0.0.1', function() {}); - -var server2 = http.createServer(dontCall); -server2.listen(common.PORT, '127.0.0.1', dontCall); - -server2.on('error', function(e) { - assert.equal(e.code, 'EADDRINUSE'); - server1.close(); - gotError = true; -}); - diff --git a/test/simple/test-http-blank-header.js b/test/simple/test-http-blank-header.js deleted file mode 100644 index bd9be8610..000000000 --- a/test/simple/test-http-blank-header.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var gotReq = false; - -var server = http.createServer(function(req, res) { - common.error('got req'); - gotReq = true; - assert.equal('GET', req.method); - assert.equal('/blah', req.url); - assert.deepEqual({ - host: 'mapdevel.trolologames.ru:443', - origin: 'http://mapdevel.trolologames.ru', - cookie: '' - }, req.headers); -}); - - -server.listen(common.PORT, function() { - var c = net.createConnection(common.PORT); - - c.on('connect', function() { - common.error('client wrote message'); - c.write('GET /blah HTTP/1.1\r\n' + - 'Host: mapdevel.trolologames.ru:443\r\n' + - 'Cookie:\r\n' + - 'Origin: http://mapdevel.trolologames.ru\r\n' + - '\r\n\r\nhello world' - ); - }); - - c.on('end', function() { - c.end(); - }); - - c.on('close', function() { - common.error('client close'); - server.close(); - }); -}); - - -process.on('exit', function() { - assert.ok(gotReq); -}); diff --git a/test/simple/test-http-buffer-sanity.js b/test/simple/test-http-buffer-sanity.js deleted file mode 100644 index 2e650d9b2..000000000 --- a/test/simple/test-http-buffer-sanity.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); - -var bufferSize = 5 * 1024 * 1024; -var measuredSize = 0; - -var buffer = Buffer(bufferSize); -for (var i = 0; i < buffer.length; i++) { - buffer[i] = i % 256; -} - - -var web = http.Server(function(req, res) { - web.close(); - - console.log(req.headers); - - var i = 0; - - req.on('data', function(d) { - process.stdout.write(','); - measuredSize += d.length; - for (var j = 0; j < d.length; j++) { - assert.equal(buffer[i], d[j]); - i++; - } - }); - - - req.on('end', function() { - res.writeHead(200); - res.write('thanks'); - res.end(); - console.log('response with \'thanks\''); - }); - - req.connection.on('error', function(e) { - console.log('http server-side error: ' + e.message); - process.exit(1); - }); -}); - -var gotThanks = false; - -web.listen(common.PORT, function() { - console.log('Making request'); - - var req = http.request({ - port: common.PORT, - method: 'GET', - path: '/', - headers: { 'content-length': buffer.length } - }, function(res) { - console.log('Got response'); - res.setEncoding('utf8'); - res.on('data', function(string) { - assert.equal('thanks', string); - gotThanks = true; - }); - }); - req.end(buffer); -}); - - -process.on('exit', function() { - assert.equal(bufferSize, measuredSize); - assert.ok(gotThanks); -}); diff --git a/test/simple/test-http-byteswritten.js b/test/simple/test-http-byteswritten.js deleted file mode 100644 index dedc2399c..000000000 --- a/test/simple/test-http-byteswritten.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var http = require('http'); - -var body = 'hello world\n'; - -var sawFinish = false; -process.on('exit', function() { - assert(sawFinish); - console.log('ok'); -}); - -var httpServer = http.createServer(function(req, res) { - httpServer.close(); - - res.on('finish', function() { - sawFinish = true; - assert(typeof(req.connection.bytesWritten) === 'number'); - assert(req.connection.bytesWritten > 0); - }); - res.writeHead(200, { 'Content-Type': 'text/plain' }); - - // Write 1.5mb to cause some requests to buffer - // Also, mix up the encodings a bit. - var chunk = new Array(1024 + 1).join('7'); - var bchunk = new Buffer(chunk); - for (var i = 0; i < 1024; i++) { - res.write(chunk); - res.write(bchunk); - res.write(chunk, 'hex'); - } - // Get .bytesWritten while buffer is not empty - assert(res.connection.bytesWritten > 0); - - res.end(body); -}); - -httpServer.listen(common.PORT, function() { - http.get({ port: common.PORT }); -}); - diff --git a/test/simple/test-http-chunked-304.js b/test/simple/test-http-chunked-304.js deleted file mode 100644 index 24c5fa151..000000000 --- a/test/simple/test-http-chunked-304.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -// RFC 2616, section 10.2.5: -// -// The 204 response MUST NOT contain a message-body, and thus is always -// terminated by the first empty line after the header fields. -// -// Likewise for 304 responses. Verify that no empty chunk is sent when -// the user explicitly sets a Transfer-Encoding header. - -test(204, function() { - test(304); -}); - -function test(statusCode, next) { - var server = http.createServer(function(req, res) { - res.writeHead(statusCode, { 'Transfer-Encoding': 'chunked' }); - res.end(); - server.close(); - }); - - server.listen(common.PORT, function() { - var conn = net.createConnection(common.PORT, function() { - conn.write('GET / HTTP/1.1\r\n\r\n'); - - var resp = ''; - conn.setEncoding('utf8'); - conn.on('data', function(data) { - resp += data; - }); - - conn.on('end', common.mustCall(function() { - assert.equal(/^Connection: close\r\n$/m.test(resp), true); - assert.equal(/^0\r\n$/m.test(resp), false); - if (next) process.nextTick(next); - })); - }); - }); -} diff --git a/test/simple/test-http-chunked.js b/test/simple/test-http-chunked.js deleted file mode 100644 index c5def3de7..000000000 --- a/test/simple/test-http-chunked.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + - '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + - '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + - '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + - '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + - '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + - '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + - '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + - '有效的改善了岭南地区落后的政治、经济现状。'; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); - res.end(UTF8_STRING, 'utf8'); -}); -server.listen(common.PORT, function() { - var data = ''; - var get = http.get({ - path: '/', - host: 'localhost', - port: common.PORT - }, function(x) { - x.setEncoding('utf8'); - x.on('data', function(c) {data += c}); - x.on('error', function(e) { - throw e; - }); - x.on('end', function() { - assert.equal('string', typeof data); - console.log('here is the response:'); - assert.equal(UTF8_STRING, data); - console.log(data); - server.close(); - }); - }); - get.on('error', function(e) {throw e}); - get.end(); - -}); diff --git a/test/simple/test-http-client-abort.js b/test/simple/test-http-client-abort.js deleted file mode 100644 index ae0ee2769..000000000 --- a/test/simple/test-http-client-abort.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var clientAborts = 0; - -var server = http.Server(function(req, res) { - console.log('Got connection'); - res.writeHead(200); - res.write('Working on it...'); - - // I would expect an error event from req or res that the client aborted - // before completing the HTTP request / response cycle, or maybe a new - // event like "aborted" or something. - req.on('aborted', function() { - clientAborts++; - console.log('Got abort ' + clientAborts); - if (clientAborts === N) { - console.log('All aborts detected, you win.'); - server.close(); - } - }); - - // since there is already clientError, maybe that would be appropriate, - // since "error" is magical - req.on('clientError', function() { - console.log('Got clientError'); - }); -}); - -var responses = 0; -var N = 16; -var requests = []; - -server.listen(common.PORT, function() { - console.log('Server listening.'); - - for (var i = 0; i < N; i++) { - console.log('Making client ' + i); - var options = { port: common.PORT, path: '/?id=' + i }; - var req = http.get(options, function(res) { - console.log('Client response code ' + res.statusCode); - - res.resume(); - if (++responses == N) { - console.log('All clients connected, destroying.'); - requests.forEach(function(outReq) { - console.log('abort'); - outReq.abort(); - }); - } - }); - - requests.push(req); - } -}); - -process.on('exit', function() { - assert.equal(N, clientAborts); -}); diff --git a/test/simple/test-http-client-abort2.js b/test/simple/test-http-client-abort2.js deleted file mode 100644 index 17efb7e08..000000000 --- a/test/simple/test-http-client-abort2.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.createServer(function(req, res) { - res.end('Hello'); -}); - -server.listen(common.PORT, function() { - var req = http.get({port: common.PORT}, function(res) { - res.on('data', function(data) { - req.abort(); - server.close(); - }); - }); -}); - diff --git a/test/simple/test-http-client-agent.js b/test/simple/test-http-client-agent.js deleted file mode 100644 index 49ff77fc9..000000000 --- a/test/simple/test-http-client-agent.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var name = http.globalAgent.getName({ port: common.PORT }); -var max = 3; -var count = 0; - -var server = http.Server(function(req, res) { - if (req.url === '/0') { - setTimeout(function() { - res.writeHead(200); - res.end('Hello, World!'); - }, 100); - } else { - res.writeHead(200); - res.end('Hello, World!'); - } -}); -server.listen(common.PORT, function() { - for (var i = 0; i < max; ++i) { - request(i); - } -}); - -function request(i) { - var req = http.get({ - port: common.PORT, - path: '/' + i - }, function(res) { - var socket = req.socket; - socket.on('close', function() { - ++count; - if (count < max) { - assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); - } else { - assert(!http.globalAgent.sockets.hasOwnProperty(name)); - assert(!http.globalAgent.requests.hasOwnProperty(name)); - server.close(); - } - }); - res.resume(); - }); -} - -process.on('exit', function() { - assert.equal(count, max); -}); diff --git a/test/simple/test-http-client-default-headers-exist.js b/test/simple/test-http-client-default-headers-exist.js deleted file mode 100644 index 24470b95d..000000000 --- a/test/simple/test-http-client-default-headers-exist.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var expectedHeaders = { - 'DELETE': ['host', 'connection'], - 'GET': ['host', 'connection'], - 'HEAD': ['host', 'connection'], - 'OPTIONS': ['host', 'connection'], - 'POST': ['host', 'connection', 'transfer-encoding'], - 'PUT': ['host', 'connection', 'transfer-encoding'] -}; - -var expectedMethods = Object.keys(expectedHeaders); - -var requestCount = 0; - -var server = http.createServer(function(req, res) { - requestCount++; - res.end(); - - assert(expectedHeaders.hasOwnProperty(req.method), - req.method + ' was an unexpected method'); - - var requestHeaders = Object.keys(req.headers); - requestHeaders.forEach(function(header) { - assert(expectedHeaders[req.method].indexOf(header.toLowerCase()) !== -1, - header + ' shoud not exist for method ' + req.method); - }); - - assert(requestHeaders.length === expectedHeaders[req.method].length, - 'some headers were missing for method: ' + req.method); - - if (expectedMethods.length === requestCount) - server.close(); -}); - -server.listen(common.PORT, function() { - expectedMethods.forEach(function(method) { - http.request({ - method: method, - port: common.PORT - }).end(); - }); -}); diff --git a/test/simple/test-http-client-encoding.js b/test/simple/test-http-client-encoding.js deleted file mode 100644 index 104bf28e2..000000000 --- a/test/simple/test-http-client-encoding.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -http.createServer(function(req, res) { - res.end('ok\n'); - this.close(); -}).listen(common.PORT, test); - -function test() { - http.request({ - port: common.PORT, - encoding: 'utf8' - }, function(res) { - res.pipe(process.stdout); - }).end(); -} diff --git a/test/simple/test-http-client-get-url.js b/test/simple/test-http-client-get-url.js deleted file mode 100644 index 451f5eeaa..000000000 --- a/test/simple/test-http-client-get-url.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var seen_req = false; - -var server = http.createServer(function(req, res) { - assert.equal('GET', req.method); - assert.equal('/foo?bar', req.url); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello\n'); - res.end(); - server.close(); - seen_req = true; -}); - -server.listen(common.PORT, function() { - http.get('http://127.0.0.1:' + common.PORT + '/foo?bar'); -}); - -process.on('exit', function() { - assert(seen_req); -}); diff --git a/test/simple/test-http-client-parse-error.js b/test/simple/test-http-client-parse-error.js deleted file mode 100644 index 9896ca225..000000000 --- a/test/simple/test-http-client-parse-error.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var net = require('net'); - -var connects = 0; -var parseErrors = 0; - -// Create a TCP server -net.createServer(function(c) { - console.log('connection'); - if (++connects === 1) { - c.end('HTTP/1.1 302 Object Moved\r\nContent-Length: 0\r\n\r\nhi world'); - } else { - c.end('bad http - should trigger parse error\r\n'); - this.close(); - } -}).listen(common.PORT, '127.0.0.1', function() { - for (var i = 0; i < 2; i++) { - http.request({ - host: '127.0.0.1', - port: common.PORT, - method: 'GET', - path: '/' - }).on('error', function(e) { - console.log('got error from client'); - assert.ok(e.message.indexOf('Parse Error') >= 0); - assert.equal(e.code, 'HPE_INVALID_CONSTANT'); - parseErrors++; - }).end(); - } -}); - -process.on('exit', function() { - assert.equal(connects, 2); - assert.equal(parseErrors, 2); -}); diff --git a/test/simple/test-http-client-pipe-end.js b/test/simple/test-http-client-pipe-end.js deleted file mode 100644 index 51edebbe1..000000000 --- a/test/simple/test-http-client-pipe-end.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// see https://github.com/joyent/node/issues/3257 - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.createServer(function(req, res) { - req.resume(); - req.once('end', function() { - res.writeHead(200); - res.end(); - server.close(); - }); -}); - -server.listen(common.PIPE, function() { - var req = http.request({ - socketPath: common.PIPE, - headers: {'Content-Length':'1'}, - method: 'POST', - path: '/' - }); - - req.write('.'); - - sched(function() { req.end() }, 5); -}); - -// schedule a callback after `ticks` event loop ticks -function sched(cb, ticks) { - function fn() { - if (--ticks) - setImmediate(fn); - else - cb(); - } - setImmediate(fn); -} diff --git a/test/simple/test-http-client-race-2.js b/test/simple/test-http-client-race-2.js deleted file mode 100644 index 6b7c508c3..000000000 --- a/test/simple/test-http-client-race-2.js +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -// -// Slight variation on test-http-client-race to test for another race -// condition involving the parsers FreeList used internally by http.Client. -// - -var body1_s = '1111111111111111'; -var body2_s = '22222'; -var body3_s = '3333333333333333333'; - -var server = http.createServer(function(req, res) { - var pathname = url.parse(req.url).pathname; - - var body; - switch (pathname) { - case '/1': body = body1_s; break; - case '/2': body = body2_s; break; - default: body = body3_s; - } - - res.writeHead(200, - {'Content-Type': 'text/plain', 'Content-Length': body.length}); - res.end(body); -}); -server.listen(common.PORT); - -var body1 = ''; -var body2 = ''; -var body3 = ''; - -server.on('listening', function() { - var client = http.createClient(common.PORT); - - // - // Client #1 is assigned Parser #1 - // - var req1 = client.request('/1'); - req1.end(); - req1.on('response', function(res1) { - res1.setEncoding('utf8'); - - res1.on('data', function(chunk) { - body1 += chunk; - }); - - res1.on('end', function() { - // - // Delay execution a little to allow the 'close' event to be processed - // (required to trigger this bug!) - // - setTimeout(function() { - // - // The bug would introduce itself here: Client #2 would be allocated the - // parser that previously belonged to Client #1. But we're not finished - // with Client #1 yet! - // - var client2 = http.createClient(common.PORT); - - // - // At this point, the bug would manifest itself and crash because the - // internal state of the parser was no longer valid for use by Client #1 - // - var req2 = client.request('/2'); - req2.end(); - req2.on('response', function(res2) { - res2.setEncoding('utf8'); - res2.on('data', function(chunk) { body2 += chunk; }); - res2.on('end', function() { - - // - // Just to be really sure we've covered all our bases, execute a - // request using client2. - // - var req3 = client2.request('/3'); - req3.end(); - req3.on('response', function(res3) { - res3.setEncoding('utf8'); - res3.on('data', function(chunk) { body3 += chunk }); - res3.on('end', function() { server.close(); }); - }); - }); - }); - }, 500); - }); - }); -}); - -process.on('exit', function() { - assert.equal(body1_s, body1); - assert.equal(body2_s, body2); - assert.equal(body3_s, body3); -}); - diff --git a/test/simple/test-http-client-race.js b/test/simple/test-http-client-race.js deleted file mode 100644 index 0f50c8e84..000000000 --- a/test/simple/test-http-client-race.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -var body1_s = '1111111111111111'; -var body2_s = '22222'; - -var server = http.createServer(function(req, res) { - var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; - res.writeHead(200, - {'Content-Type': 'text/plain', 'Content-Length': body.length}); - res.end(body); -}); -server.listen(common.PORT); - -var body1 = ''; -var body2 = ''; - -server.on('listening', function() { - var req1 = http.request({ port: common.PORT, path: '/1' }); - req1.end(); - req1.on('response', function(res1) { - res1.setEncoding('utf8'); - - res1.on('data', function(chunk) { - body1 += chunk; - }); - - res1.on('end', function() { - var req2 = http.request({ port: common.PORT, path: '/2' }); - req2.end(); - req2.on('response', function(res2) { - res2.setEncoding('utf8'); - res2.on('data', function(chunk) { body2 += chunk; }); - res2.on('end', function() { server.close(); }); - }); - }); - }); -}); - -process.on('exit', function() { - assert.equal(body1_s, body1); - assert.equal(body2_s, body2); -}); diff --git a/test/simple/test-http-client-readable.js b/test/simple/test-http-client-readable.js deleted file mode 100644 index 2b5f67562..000000000 --- a/test/simple/test-http-client-readable.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); - -var Duplex = require('stream').Duplex; - -function FakeAgent() { - http.Agent.call(this); -} -util.inherits(FakeAgent, http.Agent); - -FakeAgent.prototype.createConnection = function createConnection() { - var s = new Duplex(); - var once = false; - - s._read = function read() { - if (once) - return this.push(null); - once = true; - - this.push('HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\n\r\n'); - this.push('b\r\nhello world\r\n'); - this.readable = false; - this.push('0\r\n\r\n'); - }; - - // Blackhole - s._write = function write(data, enc, cb) { - cb(); - }; - - s.destroy = s.destroySoon = function destroy() { - this.writable = false; - }; - - return s; -}; - -var received = ''; -var ended = 0; - -var req = http.request({ - agent: new FakeAgent() -}, function(res) { - res.on('data', function(chunk) { - received += chunk; - }); - - res.on('end', function() { - ended++; - }); -}); -req.end(); - -process.on('exit', function() { - assert.equal(received, 'hello world'); - assert.equal(ended, 1); -}); diff --git a/test/simple/test-http-client-response-domain.js b/test/simple/test-http-client-response-domain.js deleted file mode 100644 index e5a39913f..000000000 --- a/test/simple/test-http-client-response-domain.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - http = require('http'), - domain = require('domain'); - -var gotDomainError = false; -var d; - -process.on('exit', function() { - assert(gotDomainError); -}); - -// first fire up a simple HTTP server -var server = http.createServer(function(req, res) { - res.writeHead(200); - res.end(); - server.close(); -}); -server.listen(common.PIPE, function() { - // create a domain - d = domain.create(); - d.run(test); -}); - -function test() { - - d.on('error', function(err) { - gotDomainError = true; - assert.equal('should be caught by domain', err.message); - }); - - var req = http.get({ - socketPath: common.PIPE, - headers: {'Content-Length':'1'}, - method: 'POST', - path: '/' - }); - req.on('response', function(res) { - res.on('end', function() { - res.emit('error', new Error('should be caught by domain')); - }); - res.resume(); - }); - req.end(); -} diff --git a/test/simple/test-http-client-timeout-agent.js b/test/simple/test-http-client-timeout-agent.js deleted file mode 100644 index 79d0a2424..000000000 --- a/test/simple/test-http-client-timeout-agent.js +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var request_number = 0; -var requests_sent = 0; -var requests_done = 0; -var options = { - method: 'GET', - port: common.PORT, - host: '127.0.0.1', -}; - -//http.globalAgent.maxSockets = 15; - -var server = http.createServer(function(req, res) { - var m = /\/(.*)/.exec(req.url), - reqid = parseInt(m[1], 10); - if ( reqid % 2 ) { - // do not reply the request - } else { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write(reqid.toString()); - res.end(); - } - request_number+=1; -}); - -server.listen(options.port, options.host, function() { - var req; - - for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { - options.path = '/' + requests_sent; - req = http.request(options); - req.id = requests_sent; - req.on('response', function(res) { - res.on('data', function(data) { - console.log('res#'+this.req.id+' data:'+data); - }); - res.on('end', function(data) { - console.log('res#'+this.req.id+' end'); - requests_done += 1; - }); - }); - req.on('close', function() { - console.log('req#'+this.id+' close'); - }); - req.on('error', function() { - console.log('req#'+this.id+' error'); - this.destroy(); - }); - req.setTimeout(50, function () { - var req = this; - console.log('req#'+this.id + ' timeout'); - req.abort(); - requests_done += 1; - }); - req.end(); - } - - setTimeout(function maybeDone() { - if (requests_done >= requests_sent) { - setTimeout(function() { - server.close(); - }, 100); - } else { - setTimeout(maybeDone, 100); - } - }, 100); -}); - -process.on('exit', function() { - console.error('done=%j sent=%j', requests_done, requests_sent); - assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); -}); diff --git a/test/simple/test-http-client-timeout-event.js b/test/simple/test-http-client-timeout-event.js deleted file mode 100644 index e3e37f699..000000000 --- a/test/simple/test-http-client-timeout-event.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var options = { - method: 'GET', - port: common.PORT, - host: '127.0.0.1', - path: '/' -}; - -var server = http.createServer(function(req, res) { - // this space intentionally left blank -}); - -server.listen(options.port, options.host, function() { - var req = http.request(options, function(res) { - // this space intentionally left blank - }); - req.on('error', function() { - // this space is intentionally left blank - }); - req.on('close', function() { - server.close(); - }); - - var timeout_events = 0; - req.setTimeout(1); - req.on('timeout', function () { - timeout_events += 1; - }); - setTimeout(function () { - req.destroy(); - assert.equal(timeout_events, 1); - }, 100); - setTimeout(function () { - req.end(); - }, 50); -}); diff --git a/test/simple/test-http-client-timeout-with-data.js b/test/simple/test-http-client-timeout-with-data.js deleted file mode 100644 index 4e1aae6ff..000000000 --- a/test/simple/test-http-client-timeout-with-data.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var ntimeouts = 0; -var nchunks = 0; - -process.on('exit', function() { - assert.equal(ntimeouts, 1); - assert.equal(nchunks, 2); -}); - -var options = { - method: 'GET', - port: common.PORT, - host: '127.0.0.1', - path: '/' -}; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length':'2'}); - res.write('*'); - setTimeout(function() { res.end('*') }, 100); -}); - -server.listen(options.port, options.host, function() { - var req = http.request(options, onresponse); - req.end(); - - function onresponse(res) { - req.setTimeout(50, function() { - assert.equal(nchunks, 1); // should have received the first chunk by now - ntimeouts++; - }); - - res.on('data', function(data) { - assert.equal('' + data, '*'); - nchunks++; - }); - - res.on('end', function() { - assert.equal(nchunks, 2); - server.close(); - }); - } -}); diff --git a/test/simple/test-http-client-timeout.js b/test/simple/test-http-client-timeout.js deleted file mode 100644 index 98eb5539e..000000000 --- a/test/simple/test-http-client-timeout.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var options = { - method: 'GET', - port: common.PORT, - host: '127.0.0.1', - path: '/' -}; - -var server = http.createServer(function(req, res) { - // this space intentionally left blank -}); - -server.listen(options.port, options.host, function() { - var req = http.request(options, function(res) { - // this space intentionally left blank - }); - req.on('close', function() { - server.close(); - }); - function destroy() { - req.destroy(); - } - req.setTimeout(1, destroy); - req.on('error', destroy); - req.end(); -}); diff --git a/test/simple/test-http-client-unescaped-path.js b/test/simple/test-http-client-unescaped-path.js deleted file mode 100644 index 376bca19c..000000000 --- a/test/simple/test-http-client-unescaped-path.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -assert.throws(function() { - // Path with spaces in it should throw. - http.get({ path: 'bad path' }, assert.fail); -}, /contains unescaped characters/); diff --git a/test/simple/test-http-client-upload-buf.js b/test/simple/test-http-client-upload-buf.js deleted file mode 100644 index d607ea88b..000000000 --- a/test/simple/test-http-client-upload-buf.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var N = 1024; -var bytesReceived = 0; -var server_req_complete = false; -var client_res_complete = false; - -var server = http.createServer(function(req, res) { - assert.equal('POST', req.method); - - req.on('data', function(chunk) { - bytesReceived += chunk.length; - }); - - req.on('end', function() { - server_req_complete = true; - console.log('request complete from server'); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello\n'); - res.end(); - }); -}); -server.listen(common.PORT); - -server.on('listening', function() { - var req = http.request({ - port: common.PORT, - method: 'POST', - path: '/' - }, function(res) { - res.setEncoding('utf8'); - res.on('data', function(chunk) { - console.log(chunk); - }); - res.on('end', function() { - client_res_complete = true; - server.close(); - }); - }); - - req.write(new Buffer(N)); - req.end(); - - common.error('client finished sending request'); -}); - -process.on('exit', function() { - assert.equal(N, bytesReceived); - assert.equal(true, server_req_complete); - assert.equal(true, client_res_complete); -}); diff --git a/test/simple/test-http-client-upload.js b/test/simple/test-http-client-upload.js deleted file mode 100644 index 912ca9608..000000000 --- a/test/simple/test-http-client-upload.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var sent_body = ''; -var server_req_complete = false; -var client_res_complete = false; - -var server = http.createServer(function(req, res) { - assert.equal('POST', req.method); - req.setEncoding('utf8'); - - req.on('data', function(chunk) { - console.log('server got: ' + JSON.stringify(chunk)); - sent_body += chunk; - }); - - req.on('end', function() { - server_req_complete = true; - console.log('request complete from server'); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello\n'); - res.end(); - }); -}); -server.listen(common.PORT); - -server.on('listening', function() { - var req = http.request({ - port: common.PORT, - method: 'POST', - path: '/' - }, function(res) { - res.setEncoding('utf8'); - res.on('data', function(chunk) { - console.log(chunk); - }); - res.on('end', function() { - client_res_complete = true; - server.close(); - }); - }); - - req.write('1\n'); - req.write('2\n'); - req.write('3\n'); - req.end(); - - common.error('client finished sending request'); -}); - -process.on('exit', function() { - assert.equal('1\n2\n3\n', sent_body); - assert.equal(true, server_req_complete); - assert.equal(true, client_res_complete); -}); diff --git a/test/simple/test-http-conn-reset.js b/test/simple/test-http-conn-reset.js deleted file mode 100644 index 9c293721c..000000000 --- a/test/simple/test-http-conn-reset.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var caughtError = false; - -var options = { - host: '127.0.0.1', - port: common.PORT -}; - -// start a tcp server that closes incoming connections immediately -var server = net.createServer(function(client) { - client.destroy(); - server.close(); -}); -server.listen(options.port, options.host, onListen); - -// do a GET request, expect it to fail -function onListen() { - var req = http.request(options, function(res) { - assert.ok(false, 'this should never run'); - }); - req.on('error', function(err) { - assert.equal(err.code, 'ECONNRESET'); - caughtError = true; - }); - req.end(); -} - -process.on('exit', function() { - assert.equal(caughtError, true); -}); - diff --git a/test/simple/test-http-connect.js b/test/simple/test-http-connect.js deleted file mode 100644 index 3643cec18..000000000 --- a/test/simple/test-http-connect.js +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var serverGotConnect = false; -var clientGotConnect = false; - -var server = http.createServer(function(req, res) { - assert(false); -}); -server.on('connect', function(req, socket, firstBodyChunk) { - assert.equal(req.method, 'CONNECT'); - assert.equal(req.url, 'google.com:443'); - common.debug('Server got CONNECT request'); - serverGotConnect = true; - - socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); - - var data = firstBodyChunk.toString(); - socket.on('data', function(buf) { - data += buf.toString(); - }); - socket.on('end', function() { - socket.end(data); - }); -}); -server.listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - method: 'CONNECT', - path: 'google.com:443' - }, function(res) { - assert(false); - }); - - var clientRequestClosed = false; - req.on('close', function() { - clientRequestClosed = true; - }); - - req.on('connect', function(res, socket, firstBodyChunk) { - common.debug('Client got CONNECT request'); - clientGotConnect = true; - - // Make sure this request got removed from the pool. - var name = 'localhost:' + common.PORT; - assert(!http.globalAgent.sockets.hasOwnProperty(name)); - assert(!http.globalAgent.requests.hasOwnProperty(name)); - - // Make sure this socket has detached. - assert(!socket.ondata); - assert(!socket.onend); - assert.equal(socket.listeners('connect').length, 0); - assert.equal(socket.listeners('data').length, 0); - - // the stream.Duplex onend listener - // allow 0 here, so that i can run the same test on streams1 impl - assert(socket.listeners('end').length <= 1); - - assert.equal(socket.listeners('free').length, 0); - assert.equal(socket.listeners('close').length, 0); - assert.equal(socket.listeners('error').length, 0); - assert.equal(socket.listeners('agentRemove').length, 0); - - var data = firstBodyChunk.toString(); - socket.on('data', function(buf) { - data += buf.toString(); - }); - socket.on('end', function() { - assert.equal(data, 'HeadBody'); - assert(clientRequestClosed); - server.close(); - }); - socket.write('Body'); - socket.end(); - }); - - // It is legal for the client to send some data intended for the server - // before the "200 Connection established" (or any other success or - // error code) is received. - req.write('Head'); - req.end(); -}); - -process.on('exit', function() { - assert.ok(serverGotConnect); - assert.ok(clientGotConnect); -}); diff --git a/test/simple/test-http-contentLength0.js b/test/simple/test-http-contentLength0.js deleted file mode 100644 index c7f7b6b66..000000000 --- a/test/simple/test-http-contentLength0.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var http = require('http'); - -// Simple test of Node's HTTP Client choking on a response -// with a 'Content-Length: 0 ' response header. -// I.E. a space character after the 'Content-Length' throws an `error` event. - - -var s = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': '0 '}); - res.end(); -}); -s.listen(common.PORT, function() { - - var request = http.request({ port: common.PORT }, function(response) { - console.log('STATUS: ' + response.statusCode); - s.close(); - response.resume(); - }); - - request.end(); -}); diff --git a/test/simple/test-http-createConnection.js b/test/simple/test-http-createConnection.js deleted file mode 100644 index bc29d9aee..000000000 --- a/test/simple/test-http-createConnection.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var create = 0; -var response = 0; -process.on('exit', function() { - assert.equal(1, create, 'createConnection() http option was not called'); - assert.equal(1, response, 'http server "request" callback was not called'); -}); - -var server = http.createServer(function(req, res) { - res.end(); - response++; -}).listen(common.PORT, '127.0.0.1', function() { - http.get({ createConnection: createConnection }, function (res) { - res.resume(); - server.close(); - }); -}); - -function createConnection() { - create++; - return net.createConnection(common.PORT, '127.0.0.1'); -} diff --git a/test/simple/test-http-curl-chunk-problem.js b/test/simple/test-http-curl-chunk-problem.js deleted file mode 100644 index 701624633..000000000 --- a/test/simple/test-http-curl-chunk-problem.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -// http://groups.google.com/group/nodejs/browse_thread/thread/f66cd3c960406919 -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var cp = require('child_process'); -var fs = require('fs'); - -var filename = require('path').join(common.tmpDir, 'big'); - -var count = 0; -function maybeMakeRequest() { - if (++count < 2) return; - console.log('making curl request'); - var cmd = 'curl http://127.0.0.1:' + common.PORT + '/ | openssl sha1'; - cp.exec(cmd, function(err, stdout, stderr) { - if (err) throw err; - var hex = stdout.match(/([A-Fa-f0-9]{40})/)[0]; - assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', hex); - console.log('got the correct response'); - fs.unlink(filename); - server.close(); - }); -} - - -var ddcmd = common.ddCommand(filename, 10240); -console.log('dd command: ', ddcmd); - -cp.exec(ddcmd, function(err, stdout, stderr) { - if (err) throw err; - maybeMakeRequest(); -}); - - -var server = http.createServer(function(req, res) { - res.writeHead(200); - - // Create the subprocess - var cat = cp.spawn('cat', [filename]); - - // Stream the data through to the response as binary chunks - cat.stdout.on('data', function(data) { - res.write(data); - }); - - // End the response on exit (and log errors) - cat.on('exit', function(code) { - if (code !== 0) { - console.error('subprocess exited with code ' + code); - process.exit(1); - } - res.end(); - }); - -}); - -server.listen(common.PORT, maybeMakeRequest); - -console.log('Server running at http://localhost:8080'); diff --git a/test/simple/test-http-date-header.js b/test/simple/test-http-date-header.js deleted file mode 100644 index b11507c01..000000000 --- a/test/simple/test-http-date-header.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var testResBody = 'other stuff!\n'; - -var server = http.createServer(function(req, res) { - assert.ok(! ('date' in req.headers), - 'Request headers contained a Date.'); - res.writeHead(200, { - 'Content-Type': 'text/plain' - }); - res.end(testResBody); -}); -server.listen(common.PORT); - - -server.addListener('listening', function() { - var options = { - port: common.PORT, - path: '/', - method: 'GET' - }; - var req = http.request(options, function(res) { - assert.ok('date' in res.headers, - 'Response headers didn\'t contain a Date.'); - res.addListener('end', function() { - server.close(); - process.exit(); - }); - res.resume(); - }); - req.end(); -}); diff --git a/test/simple/test-http-default-encoding.js b/test/simple/test-http-default-encoding.js deleted file mode 100644 index b06f7c83a..000000000 --- a/test/simple/test-http-default-encoding.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var expected = 'This is a unicode text: سلام'; -var result = ''; - -var server = http.Server(function(req, res) { - req.setEncoding('utf8'); - req.on('data', function(chunk) { - result += chunk; - }).on('end', function() { - clearTimeout(timeout); - server.close(); - }); - - var timeout = setTimeout(function() { - process.exit(1); - }, 100); - - res.writeHead(200); - res.end('hello world\n'); -}); - -server.listen(common.PORT, function() { - http.request({ - port: common.PORT, - path: '/', - method: 'POST' - }, function(res) { - console.log(res.statusCode); - res.resume(); - }).on('error', function(e) { - console.log(e.message); - process.exit(1); - }).end(expected); -}); - -process.on('exit', function() { - assert.equal(expected, result); -}); diff --git a/test/simple/test-http-default-port.js b/test/simple/test-http-default-port.js deleted file mode 100644 index ec79de2ae..000000000 --- a/test/simple/test-http-default-port.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var common = require('../common'); -var http = require('http'), - https = require('https'), - PORT = common.PORT, - SSLPORT = common.PORT + 1, - assert = require('assert'), - hostExpect = 'localhost', - fs = require('fs'), - path = require('path'), - fixtures = path.resolve(__dirname, '../fixtures/keys'), - options = { - key: fs.readFileSync(fixtures + '/agent1-key.pem'), - cert: fs.readFileSync(fixtures + '/agent1-cert.pem') - }, - gotHttpsResp = false, - gotHttpResp = false; - -process.on('exit', function() { - assert(gotHttpsResp); - assert(gotHttpResp); - console.log('ok'); -}); - -http.globalAgent.defaultPort = PORT; -https.globalAgent.defaultPort = SSLPORT; - -http.createServer(function(req, res) { - assert.equal(req.headers.host, hostExpect); - assert.equal(req.headers['x-port'], PORT); - res.writeHead(200); - res.end('ok'); - this.close(); -}).listen(PORT, function() { - http.get({ - host: 'localhost', - headers: { - 'x-port': PORT - } - }, function(res) { - gotHttpResp = true; - res.resume(); - }); -}); - -https.createServer(options, function(req, res) { - assert.equal(req.headers.host, hostExpect); - assert.equal(req.headers['x-port'], SSLPORT); - res.writeHead(200); - res.end('ok'); - this.close(); -}).listen(SSLPORT, function() { - var req = https.get({ - host: 'localhost', - rejectUnauthorized: false, - headers: { - 'x-port': SSLPORT - } - }, function(res) { - gotHttpsResp = true; - res.resume(); - }); -}); diff --git a/test/simple/test-http-destroyed-socket-write2.js b/test/simple/test-http-destroyed-socket-write2.js deleted file mode 100644 index 3347f3ccc..000000000 --- a/test/simple/test-http-destroyed-socket-write2.js +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// Verify that ECONNRESET is raised when writing to a http request -// where the server has ended the socket. - -var http = require('http'); -var net = require('net'); -var server = http.createServer(function(req, res) { - setImmediate(function() { - res.destroy(); - }); -}); - -server.listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - path: '/', - method: 'POST' - }); - - var timer = setImmediate(write); - var writes = 0; - - function write() { - if (++writes === 128) { - clearTimeout(timer); - req.end(); - test(); - } else { - timer = setImmediate(write); - req.write('hello'); - } - } - - var gotError = false; - var sawData = false; - var sawEnd = false; - - req.on('error', function(er) { - assert(!gotError); - gotError = true; - switch (er.code) { - // This is the expected case - case 'ECONNRESET': - // On windows this sometimes manifests as ECONNABORTED - case 'ECONNABORTED': - break; - default: - assert.strictEqual(er.code, - 'ECONNRESET', - 'Writing to a torn down client should RESET or ABORT'); - break; - } - clearTimeout(timer); - console.log('ECONNRESET was raised after %d writes', writes); - test(); - }); - - req.on('response', function(res) { - res.on('data', function(chunk) { - console.error('saw data: ' + chunk); - sawData = true; - }); - res.on('end', function() { - console.error('saw end'); - sawEnd = true; - }); - }); - - var closed = false; - - function test() { - if (closed) - return; - - server.close(); - closed = true; - - if (req.output.length || req.outputEncodings.length) - console.error('bad happened', req.output, req.outputEncodings); - - assert.equal(req.output.length, 0); - assert.equal(req.outputEncodings, 0); - assert(gotError); - assert(!sawData); - assert(!sawEnd); - console.log('ok'); - } -}); diff --git a/test/simple/test-http-dns-error.js b/test/simple/test-http-dns-error.js deleted file mode 100644 index fc6d6b89e..000000000 --- a/test/simple/test-http-dns-error.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var https = require('https'); - -var expected_bad_requests = 0; -var actual_bad_requests = 0; - -var host = '********'; -host += host; -host += host; -host += host; -host += host; -host += host; - -function do_not_call() { - throw new Error('This function should not have been called.'); -} - -function test(mod) { - expected_bad_requests += 2; - - // Bad host name should not throw an uncatchable exception. - // Ensure that there is time to attach an error listener. - var req = mod.get({host: host, port: 42}, do_not_call); - req.on('error', function(err) { - assert.equal(err.code, 'ENOTFOUND'); - actual_bad_requests++; - }); - // http.get() called req.end() for us - - var req = mod.request({method: 'GET', host: host, port: 42}, do_not_call); - req.on('error', function(err) { - assert.equal(err.code, 'ENOTFOUND'); - actual_bad_requests++; - }); - req.end(); -} - -test(https); -test(http); - -process.on('exit', function() { - assert.equal(actual_bad_requests, expected_bad_requests); -}); - diff --git a/test/simple/test-http-end-throw-socket-handling.js b/test/simple/test-http-end-throw-socket-handling.js deleted file mode 100644 index 50aa97ff1..000000000 --- a/test/simple/test-http-end-throw-socket-handling.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// Make sure that throwing in 'end' handler doesn't lock -// up the socket forever. -// -// This is NOT a good way to handle errors in general, but all -// the same, we should not be so brittle and easily broken. - -var http = require('http'); - -var n = 0; -var server = http.createServer(function(req, res) { - if (++n === 10) server.close(); - res.end('ok'); -}); - -server.listen(common.PORT, function() { - for (var i = 0; i < 10; i++) { - var options = { port: common.PORT }; - - var req = http.request(options, function (res) { - res.resume() - res.on('end', function() { - throw new Error('gleep glorp'); - }); - }); - req.end(); - } -}); - -setTimeout(function() { - process.removeListener('uncaughtException', catcher); - throw new Error('Taking too long!'); -}, 1000).unref(); - -process.on('uncaughtException', catcher); -var errors = 0; -function catcher() { - errors++; -} - -process.on('exit', function() { - assert.equal(errors, 10); - console.log('ok'); -}); diff --git a/test/simple/test-http-eof-on-connect.js b/test/simple/test-http-eof-on-connect.js deleted file mode 100644 index 95d6fdc95..000000000 --- a/test/simple/test-http-eof-on-connect.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); - -// This is a regression test for https://github.com/joyent/node/issues/44 -// It is separate from test-http-malformed-request.js because it is only -// reproduceable on the first packet on the first connection to a server. - -var server = http.createServer(function(req, res) {}); -server.listen(common.PORT); - -server.on('listening', function() { - net.createConnection(common.PORT).on('connect', function() { - this.destroy(); - }).on('close', function() { - server.close(); - }); -}); diff --git a/test/simple/test-http-exceptions.js b/test/simple/test-http-exceptions.js deleted file mode 100644 index 1501d944a..000000000 --- a/test/simple/test-http-exceptions.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.createServer(function(req, res) { - intentionally_not_defined(); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('Thank you, come again.'); - res.end(); -}); - -server.listen(common.PORT, function() { - var req; - for (var i = 0; i < 4; i += 1) { - req = http.get({ port: common.PORT, path: '/busy/' + i }); - } -}); - -var exception_count = 0; - -process.on('uncaughtException', function(err) { - console.log('Caught an exception: ' + err); - if (err.name === 'AssertionError') throw err; - if (++exception_count == 4) process.exit(0); -}); - diff --git a/test/simple/test-http-exit-delay.js b/test/simple/test-http-exit-delay.js deleted file mode 100644 index 900f4fabd..000000000 --- a/test/simple/test-http-exit-delay.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common.js'); -var http = require('http'); - -var start; -var server = http.createServer(function(req, res) { - req.resume(); - req.on('end', function() { - res.end('Success'); - }); - - server.close(); -}); - -server.listen(common.PORT, 'localhost', function() { - var interval_id = setInterval(function() { - start = new Date(); - if (start.getMilliseconds() > 100) - return; - - console.log(start.toISOString()); - var req = http.request({ - 'host': 'localhost', - 'port': common.PORT, - 'agent': false, - 'method': 'PUT' - }); - - req.end('Test'); - clearInterval(interval_id); - }, 10); -}); - -process.on('exit', function() { - var end = new Date(); - console.log(end.toISOString()); - assert.equal(start.getSeconds(), end.getSeconds()); - assert(end.getMilliseconds() < 900); - console.log('ok'); -}); diff --git a/test/simple/test-http-expect-continue.js b/test/simple/test-http-expect-continue.js deleted file mode 100644 index 54c04cce0..000000000 --- a/test/simple/test-http-expect-continue.js +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var outstanding_reqs = 0; -var test_req_body = 'some stuff...\n'; -var test_res_body = 'other stuff!\n'; -var sent_continue = false; -var got_continue = false; - -function handler(req, res) { - assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); - common.debug('Server sending full response...'); - res.writeHead(200, { - 'Content-Type' : 'text/plain', - 'ABCD' : '1' - }); - res.end(test_res_body); -} - -var server = http.createServer(handler); -server.on('checkContinue', function(req, res) { - common.debug('Server got Expect: 100-continue...'); - res.writeContinue(); - sent_continue = true; - setTimeout(function() { - handler(req, res); - }, 100); -}); -server.listen(common.PORT); - - - -server.on('listening', function() { - var req = http.request({ - port: common.PORT, - method: 'POST', - path: '/world', - headers: { 'Expect': '100-continue' } - }); - common.debug('Client sending request...'); - outstanding_reqs++; - var body = ''; - req.on('continue', function() { - common.debug('Client got 100 Continue...'); - got_continue = true; - req.end(test_req_body); - }); - req.on('response', function(res) { - assert.equal(got_continue, true, - 'Full response received before 100 Continue'); - assert.equal(200, res.statusCode, - 'Final status code was ' + res.statusCode + ', not 200.'); - res.setEncoding('utf8'); - res.on('data', function(chunk) { body += chunk; }); - res.on('end', function() { - common.debug('Got full response.'); - assert.equal(body, test_res_body, 'Response body doesn\'t match.'); - assert.ok('abcd' in res.headers, 'Response headers missing.'); - outstanding_reqs--; - if (outstanding_reqs == 0) { - server.close(); - process.exit(); - } - }); - }); -}); diff --git a/test/simple/test-http-extra-response.js b/test/simple/test-http-extra-response.js deleted file mode 100644 index 1649a6a92..000000000 --- a/test/simple/test-http-extra-response.js +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -// If an HTTP server is broken and sends data after the end of the response, -// node should ignore it and drop the connection. -// Demos this bug: https://github.com/joyent/node/issues/680 - -var body = 'hello world\r\n'; -var fullResponse = - 'HTTP/1.1 500 Internal Server Error\r\n' + - 'Content-Length: ' + body.length + '\r\n' + - 'Content-Type: text/plain\r\n' + - 'Date: Fri + 18 Feb 2011 06:22:45 GMT\r\n' + - 'Host: 10.20.149.2\r\n' + - 'Access-Control-Allow-Credentials: true\r\n' + - 'Server: badly broken/0.1 (OS NAME)\r\n' + - '\r\n' + - body; - -var gotResponse = false; - - -var server = net.createServer(function(socket) { - var postBody = ''; - - socket.setEncoding('utf8'); - - socket.on('data', function(chunk) { - postBody += chunk; - - if (postBody.indexOf('\r\n') > -1) { - socket.write(fullResponse); - // omg, I wrote the response twice, what a terrible HTTP server I am. - socket.end(fullResponse); - } - }); -}); - - -server.listen(common.PORT, function() { - http.get({ port: common.PORT }, function(res) { - var buffer = ''; - console.log('Got res code: ' + res.statusCode); - - res.setEncoding('utf8'); - res.on('data', function(chunk) { - buffer += chunk; - }); - - res.on('end', function() { - console.log('Response ended, read ' + buffer.length + ' bytes'); - assert.equal(body, buffer); - server.close(); - gotResponse = true; - }); - }); -}); - - -process.on('exit', function() { - assert.ok(gotResponse); -}); - diff --git a/test/simple/test-http-flush.js b/test/simple/test-http-flush.js deleted file mode 100644 index 842cf8729..000000000 --- a/test/simple/test-http-flush.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -http.createServer(function(req, res) { - res.end('ok'); - this.close(); -}).listen(common.PORT, '127.0.0.1', function() { - var req = http.request({ - method: 'POST', - host: '127.0.0.1', - port: common.PORT, - }); - req.flush(); // Flush the request headers. - req.flush(); // Should be idempotent. -}); diff --git a/test/simple/test-http-full-response.js b/test/simple/test-http-full-response.js deleted file mode 100644 index d33df8b88..000000000 --- a/test/simple/test-http-full-response.js +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -// This test requires the program 'ab' -var http = require('http'); -var exec = require('child_process').exec; - -var bodyLength = 12345; - -var body = ''; -for (var i = 0; i < bodyLength; i++) { - body += 'c'; -} - -var server = http.createServer(function(req, res) { - res.writeHead(200, { - 'Content-Length': bodyLength, - 'Content-Type': 'text/plain' - }); - res.end(body); -}); - -var runs = 0; - -function runAb(opts, callback) { - var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/'; - exec(command, function(err, stdout, stderr) { - if (err) { - if (/ab|apr/mi.test(stderr)) { - console.log('problem spawning ab - skipping test.\n' + stderr); - process.reallyExit(0); - } - process.exit(); - return; - } - - var m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); - var documentLength = parseInt(m[1]); - - var m = /Complete requests:\s*(\d+)/mi.exec(stdout); - var completeRequests = parseInt(m[1]); - - var m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); - var htmlTransfered = parseInt(m[1]); - - assert.equal(bodyLength, documentLength); - assert.equal(completeRequests * documentLength, htmlTransfered); - - runs++; - - if (callback) callback(); - }); -} - -server.listen(common.PORT, function() { - runAb('-c 1 -n 10', function() { - console.log('-c 1 -n 10 okay'); - - runAb('-c 1 -n 100', function() { - console.log('-c 1 -n 100 okay'); - - runAb('-c 1 -n 1000', function() { - console.log('-c 1 -n 1000 okay'); - server.close(); - }); - }); - }); - -}); - -process.on('exit', function() { - assert.equal(3, runs); -}); diff --git a/test/simple/test-http-get-pipeline-problem.js b/test/simple/test-http-get-pipeline-problem.js deleted file mode 100644 index 720ce4b89..000000000 --- a/test/simple/test-http-get-pipeline-problem.js +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -// We are demonstrating a problem with http.get when queueing up many -// transfers. The server simply introduces some delay and sends a file. -// Note this is demonstrated with connection: close. -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var fs = require('fs'); - -var image = fs.readFileSync(common.fixturesDir + '/person.jpg'); - -console.log('image.length = ' + image.length); - -var total = 100; -var requests = 0, responses = 0; - -var server = http.Server(function(req, res) { - if (++requests == total) { - server.close(); - } - - setTimeout(function() { - res.writeHead(200, { - 'content-type': 'image/jpeg', - 'connection': 'close', - 'content-length': image.length - }); - res.end(image); - }, 1); -}); - - -server.listen(common.PORT, function() { - for (var i = 0; i < total; i++) { - (function() { - var x = i; - - var opts = { - port: common.PORT, - headers: { connection: 'close' } - }; - - http.get(opts, function(res) { - console.error('recv ' + x); - var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); - res.pipe(s); - - // TODO there should be a callback to pipe() that will allow - // us to get a callback when the pipe is finished. - res.on('end', function() { - console.error('done ' + x); - if (++responses == total) { - s.on('close', checkFiles); - } - }); - }).on('error', function(e) { - console.error('error! ', e.message); - throw e; - }); - })(); - } -}); - - -var checkedFiles = false; -function checkFiles() { - // Should see 1.jpg, 2.jpg, ..., 100.jpg in tmpDir - var files = fs.readdirSync(common.tmpDir); - assert(total <= files.length); - - for (var i = 0; i < total; i++) { - var fn = i + '.jpg'; - assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); - var stat = fs.statSync(common.tmpDir + '/' + fn); - assert.equal(image.length, stat.size, - "size doesn't match on '" + fn + - "'. Got " + stat.size + ' bytes'); - } - - checkedFiles = true; -} - - -process.on('exit', function() { - assert.equal(total, requests); - assert.equal(total, responses); - assert.ok(checkedFiles); -}); diff --git a/test/simple/test-http-head-request.js b/test/simple/test-http-head-request.js deleted file mode 100644 index ca0f13a1a..000000000 --- a/test/simple/test-http-head-request.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); - - -var body = 'hello world\n'; -var id = 0; - -function test(headers) { - var port = common.PORT + id++; - - var server = http.createServer(function(req, res) { - console.error('req: %s headers: %j', req.method, headers); - res.writeHead(200, headers); - res.end(); - server.close(); - }); - - var gotEnd = false; - - server.listen(port, function() { - var request = http.request({ - port: port, - method: 'HEAD', - path: '/' - }, function(response) { - console.error('response start'); - response.on('end', function() { - console.error('response end'); - gotEnd = true; - }); - response.resume(); - }); - request.end(); - }); - - process.on('exit', function() { - assert.ok(gotEnd); - }); -} - -test({ - 'Transfer-Encoding': 'chunked' -}); -test({ - 'Content-Length': body.length -}); diff --git a/test/simple/test-http-head-response-has-no-body-end.js b/test/simple/test-http-head-response-has-no-body-end.js deleted file mode 100644 index cde777a58..000000000 --- a/test/simple/test-http-head-response-has-no-body-end.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -// This test is to make sure that when the HTTP server -// responds to a HEAD request with data to res.end, -// it does not send any body. - -var server = http.createServer(function(req, res) { - res.writeHead(200); - res.end('FAIL'); // broken: sends FAIL from hot path. -}); -server.listen(common.PORT); - -var responseComplete = false; - -server.on('listening', function() { - var req = http.request({ - port: common.PORT, - method: 'HEAD', - path: '/' - }, function(res) { - common.error('response'); - res.on('end', function() { - common.error('response end'); - server.close(); - responseComplete = true; - }); - res.resume(); - }); - common.error('req'); - req.end(); -}); - -process.on('exit', function() { - assert.ok(responseComplete); -}); diff --git a/test/simple/test-http-head-response-has-no-body.js b/test/simple/test-http-head-response-has-no-body.js deleted file mode 100644 index ab6bd5b51..000000000 --- a/test/simple/test-http-head-response-has-no-body.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -// This test is to make sure that when the HTTP server -// responds to a HEAD request, it does not send any body. -// In this case it was sending '0\r\n\r\n' - -var server = http.createServer(function(req, res) { - res.writeHead(200); // broken: defaults to TE chunked - res.end(); -}); -server.listen(common.PORT); - -var responseComplete = false; - -server.on('listening', function() { - var req = http.request({ - port: common.PORT, - method: 'HEAD', - path: '/' - }, function(res) { - common.error('response'); - res.on('end', function() { - common.error('response end'); - server.close(); - responseComplete = true; - }); - res.resume(); - }); - common.error('req'); - req.end(); -}); - -process.on('exit', function() { - assert.ok(responseComplete); -}); diff --git a/test/simple/test-http-header-read.js b/test/simple/test-http-header-read.js deleted file mode 100644 index 338377592..000000000 --- a/test/simple/test-http-header-read.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -// Verify that ServerResponse.getHeader() works correctly even after -// the response header has been sent. Issue 752 on github. - -var s = http.createServer(function(req, res) { - var contentType = 'Content-Type'; - var plain = 'text/plain'; - res.setHeader(contentType, plain); - assert.ok(!res.headersSent); - res.writeHead(200); - assert.ok(res.headersSent); - res.end('hello world\n'); - // This checks that after the headers have been sent, getHeader works - // and does not throw an exception (Issue 752) - assert.doesNotThrow( - function() { - assert.equal(plain, res.getHeader(contentType)); - } - ); -}); - -s.listen(common.PORT, runTest); - -function runTest() { - http.get({ port: common.PORT }, function(response) { - response.on('end', function() { - s.close(); - }); - response.resume(); - }); -} diff --git a/test/simple/test-http-header-response-splitting.js b/test/simple/test-http-header-response-splitting.js deleted file mode 100644 index 1d3a85ce8..000000000 --- a/test/simple/test-http-header-response-splitting.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - http = require('http'); - -var testIndex = 0, - responses = 0; - -var server = http.createServer(function(req, res) { - switch (testIndex++) { - case 0: - res.writeHead(200, { test: 'foo \r\ninvalid: bar' }); - break; - case 1: - res.writeHead(200, { test: 'foo \ninvalid: bar' }); - break; - case 2: - res.writeHead(200, { test: 'foo \rinvalid: bar' }); - break; - case 3: - res.writeHead(200, { test: 'foo \n\n\ninvalid: bar' }); - break; - case 4: - res.writeHead(200, { test: 'foo \r\n \r\n \r\ninvalid: bar' }); - server.close(); - break; - default: - assert(false); - } - res.end('Hi mars!'); -}); - -server.listen(common.PORT, function() { - for (var i = 0; i < 5; i++) { - var req = http.get({ port: common.PORT, path: '/' }, function(res) { - assert.strictEqual(res.headers.test, 'foo invalid: bar'); - assert.strictEqual(res.headers.invalid, undefined); - responses++; - res.resume(); - }); - } -}); - -process.on('exit', function() { - assert.strictEqual(responses, 5); -}); diff --git a/test/simple/test-http-hex-write.js b/test/simple/test-http-hex-write.js deleted file mode 100644 index 21a93df53..000000000 --- a/test/simple/test-http-hex-write.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var expect = 'hex\nutf8\n'; -var data = ''; -var ended = false; - -process.on('exit', function() { - assert(ended); - assert.equal(data, expect); - console.log('ok'); -}); - -http.createServer(function(q, s) { - s.setHeader('content-length', expect.length); - s.write('6865780a', 'hex'); - s.write('utf8\n'); - s.end(); - this.close(); -}).listen(common.PORT, function() { - http.request({ port: common.PORT }).on('response', function(res) { - res.setEncoding('ascii'); - res.on('data', function(c) { - data += c; - }); - res.on('end', function() { - ended = true; - }); - }).end(); -}); diff --git a/test/simple/test-http-host-headers.js b/test/simple/test-http-host-headers.js deleted file mode 100644 index ca7f70947..000000000 --- a/test/simple/test-http-host-headers.js +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var http = require('http'), - https = require('https'), - fs = require('fs'), - common = require('../common'), - assert = require('assert'), - options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') - }, - httpServer = http.createServer(reqHandler), - httpsServer = https.createServer(options, reqHandler); - -function reqHandler(req, res) { - console.log('Got request: ' + req.headers.host + ' ' + req.url); - if (req.url === '/setHostFalse5') { - assert.equal(req.headers.host, undefined); - } else { - assert.equal(req.headers.host, 'localhost:' + common.PORT, - 'Wrong host header for req[' + req.url + ']: ' + - req.headers.host); - } - res.writeHead(200, {}); - //process.nextTick(function() { res.end('ok'); }); - res.end('ok'); -} - -function thrower(er) { - throw er; -} - -testHttp(); - -function testHttp() { - - console.log('testing http on port ' + common.PORT); - - var counter = 0; - - function cb(res) { - counter--; - console.log('back from http request. counter = ' + counter); - if (counter === 0) { - httpServer.close(); - testHttps(); - } - res.resume(); - } - - httpServer.listen(common.PORT, function(er) { - console.error('listening on ' + common.PORT); - - if (er) throw er; - - http.get({ - method: 'GET', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower); - - http.request({ - method: 'GET', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - http.request({ - method: 'POST', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - http.request({ - method: 'PUT', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - http.request({ - method: 'DELETE', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - }); -} - -function testHttps() { - - console.log('testing https on port ' + common.PORT); - - var counter = 0; - - function cb(res) { - counter--; - console.log('back from https request. counter = ' + counter); - if (counter === 0) { - httpsServer.close(); - console.log('ok'); - } - res.resume(); - } - - httpsServer.listen(common.PORT, function(er) { - if (er) throw er; - - https.get({ - method: 'GET', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower); - - https.request({ - method: 'GET', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - https.request({ - method: 'POST', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - https.request({ - method: 'PUT', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - https.request({ - method: 'DELETE', - path: '/' + (counter++), - host: 'localhost', - //agent: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - - https.get({ - method: 'GET', - path: '/setHostFalse' + (counter++), - host: 'localhost', - setHost: false, - port: common.PORT, - rejectUnauthorized: false - }, cb).on('error', thrower).end(); - }); -} diff --git a/test/simple/test-http-incoming-pipelined-socket-destroy.js b/test/simple/test-http-incoming-pipelined-socket-destroy.js deleted file mode 100644 index 3a2f531a7..000000000 --- a/test/simple/test-http-incoming-pipelined-socket-destroy.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var net = require('net'); - - -// Set up some timing issues where sockets can be destroyed -// via either the req or res. -var server = http.createServer(function(req, res) { - switch (req.url) { - case '/1': - return setTimeout(function() { - req.socket.destroy(); - server.emit('requestDone'); - }); - - case '/2': - return process.nextTick(function() { - res.destroy(); - server.emit('requestDone'); - }); - - // in one case, actually send a response in 2 chunks - case '/3': - res.write('hello '); - return setTimeout(function() { - res.end('world!'); - server.emit('requestDone'); - }); - - default: - res.destroy(); - server.emit('requestDone'); - } -}); - - -// Make a bunch of requests pipelined on the same socket -function generator(seeds) { - return seeds.map(function(r) { - return 'GET /' + r + ' HTTP/1.1\r\n' + - 'Host: localhost:' + common.PORT + '\r\n' + - '\r\n' + - '\r\n' - }).join(''); -} - - -server.listen(common.PORT, function() { - var seeds = [ 3, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 ]; - var client = net.connect({ port: common.PORT }); - var done = 0; - server.on('requestDone', function() { - if (++done == seeds.length) { - server.close(); - } - }); - - // immediately write the pipelined requests. - // Some of these will not have a socket to destroy! - client.write(generator(seeds)); -}); - -process.on('exit', function(c) { - if (!c) - console.log('ok'); -}); diff --git a/test/simple/test-http-keep-alive-close-on-header.js b/test/simple/test-http-keep-alive-close-on-header.js deleted file mode 100644 index 4318bd970..000000000 --- a/test/simple/test-http-keep-alive-close-on-header.js +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); - -var body = 'hello world\n'; -var headers = {'connection': 'keep-alive'}; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); - res.write(body); - res.end(); -}); - -var connectCount = 0; - - -server.listen(common.PORT, function() { - var agent = new http.Agent({ maxSockets: 1 }); - var name = agent.getName({ port: common.PORT }); - var request = http.request({ - method: 'GET', - path: '/', - headers: headers, - port: common.PORT, - agent: agent - }, function(res) { - assert.equal(1, agent.sockets[name].length); - res.resume(); - }); - request.on('socket', function(s) { - s.on('connect', function() { - connectCount++; - }); - }); - request.end(); - - request = http.request({ - method: 'GET', - path: '/', - headers: headers, - port: common.PORT, - agent: agent - }, function(res) { - assert.equal(1, agent.sockets[name].length); - res.resume(); - }); - request.on('socket', function(s) { - s.on('connect', function() { - connectCount++; - }); - }); - request.end(); - request = http.request({ - method: 'GET', - path: '/', - headers: headers, - port: common.PORT, - agent: agent - }, function(response) { - response.on('end', function() { - assert.equal(1, agent.sockets[name].length); - server.close(); - }); - response.resume(); - }); - request.on('socket', function(s) { - s.on('connect', function() { - connectCount++; - }); - }); - request.end(); -}); - -process.on('exit', function() { - assert.equal(3, connectCount); -}); diff --git a/test/simple/test-http-keep-alive.js b/test/simple/test-http-keep-alive.js deleted file mode 100644 index 75049c9c6..000000000 --- a/test/simple/test-http-keep-alive.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var body = 'hello world\n'; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': body.length}); - res.write(body); - res.end(); -}); - -var connectCount = 0; -var agent = new http.Agent({maxSockets: 1}); -var headers = {'connection': 'keep-alive'}; -var name = agent.getName({ port: common.PORT }); - -server.listen(common.PORT, function() { - http.get({ - path: '/', headers: headers, port: common.PORT, agent: agent - }, function(response) { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.requests[name].length, 2); - response.resume(); - }); - - http.get({ - path: '/', headers: headers, port: common.PORT, agent: agent - }, function(response) { - assert.equal(agent.sockets[name].length, 1); - assert.equal(agent.requests[name].length, 1); - response.resume(); - }); - - http.get({ - path: '/', headers: headers, port: common.PORT, agent: agent - }, function(response) { - response.on('end', function() { - assert.equal(agent.sockets[name].length, 1); - assert(!agent.requests.hasOwnProperty(name)); - server.close(); - }); - response.resume(); - }); -}); - -process.on('exit', function() { - assert(!agent.sockets.hasOwnProperty(name)); - assert(!agent.requests.hasOwnProperty(name)); -}); diff --git a/test/simple/test-http-keepalive-client.js b/test/simple/test-http-keepalive-client.js deleted file mode 100644 index 177a8ed7a..000000000 --- a/test/simple/test-http-keepalive-client.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - - -var serverSocket = null; -var server = http.createServer(function(req, res) { - // They should all come in on the same server socket. - if (serverSocket) { - assert.equal(req.socket, serverSocket); - } else { - serverSocket = req.socket; - } - - res.end(req.url); -}); -server.listen(common.PORT); - -var agent = http.Agent({ keepAlive: true }); - - -var clientSocket = null; -var expectRequests = 10; -var actualRequests = 0; - - -makeRequest(expectRequests); -function makeRequest(n) { - if (n === 0) { - server.close(); - agent.destroy(); - return; - } - - var req = http.request({ - port: common.PORT, - agent: agent, - path: '/' + n - }); - - req.end(); - - req.on('socket', function(sock) { - if (clientSocket) { - assert.equal(sock, clientSocket); - } else { - clientSocket = sock; - } - }); - - req.on('response', function(res) { - var data = ''; - res.setEncoding('utf8'); - res.on('data', function(c) { - data += c; - }); - res.on('end', function() { - assert.equal(data, '/' + n); - setTimeout(function() { - actualRequests++; - makeRequest(n - 1); - }, 1); - }); - }); -} - -process.on('exit', function() { - assert.equal(actualRequests, expectRequests) - console.log('ok'); -}); diff --git a/test/simple/test-http-keepalive-maxsockets.js b/test/simple/test-http-keepalive-maxsockets.js deleted file mode 100644 index 8481eec35..000000000 --- a/test/simple/test-http-keepalive-maxsockets.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - - -var serverSockets = []; -var server = http.createServer(function(req, res) { - if (serverSockets.indexOf(req.socket) === -1) { - serverSockets.push(req.socket); - } - res.end(req.url); -}); -server.listen(common.PORT); - -var agent = http.Agent({ - keepAlive: true, - maxSockets: 5, - maxFreeSockets: 2 -}); - -// make 10 requests in parallel, -// then 10 more when they all finish. -function makeReqs(n, cb) { - for (var i = 0; i < n; i++) - makeReq(i, then); - - function then(er) { - if (er) - return cb(er); - else if (--n === 0) - setTimeout(cb, 100); - } -} - -function makeReq(i, cb) { - http.request({ - port: common.PORT, - path: '/' + i, - agent: agent - }, function(res) { - var data = ''; - res.setEncoding('ascii'); - res.on('data', function(c) { - data += c; - }); - res.on('end', function() { - assert.equal(data, '/' + i); - cb(); - }); - }).end(); -} - -var closed = false; -makeReqs(10, function(er) { - assert.ifError(er); - assert.equal(count(agent.freeSockets), 2); - assert.equal(count(agent.sockets), 0); - assert.equal(serverSockets.length, 5); - - // now make 10 more reqs. - // should use the 2 free reqs from the pool first. - makeReqs(10, function(er) { - assert.ifError(er); - assert.equal(count(agent.freeSockets), 2); - assert.equal(count(agent.sockets), 0); - assert.equal(serverSockets.length, 8); - - agent.destroy(); - server.close(function() { - closed = true; - }); - }); -}); - -function count(sockets) { - return Object.keys(sockets).reduce(function(n, name) { - return n + sockets[name].length; - }, 0); -} - -process.on('exit', function() { - assert(closed); - console.log('ok'); -}); diff --git a/test/simple/test-http-keepalive-request.js b/test/simple/test-http-keepalive-request.js deleted file mode 100644 index 3b8737540..000000000 --- a/test/simple/test-http-keepalive-request.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - - -var serverSocket = null; -var server = http.createServer(function(req, res) { - // They should all come in on the same server socket. - if (serverSocket) { - assert.equal(req.socket, serverSocket); - } else { - serverSocket = req.socket; - } - - res.end(req.url); -}); -server.listen(common.PORT); - -var agent = http.Agent({ keepAlive: true }); - - -var clientSocket = null; -var expectRequests = 10; -var actualRequests = 0; - - -makeRequest(expectRequests); -function makeRequest(n) { - if (n === 0) { - server.close(); - agent.destroy(); - return; - } - - var req = http.request({ - port: common.PORT, - path: '/' + n, - agent: agent - }); - - req.end(); - - req.on('socket', function(sock) { - if (clientSocket) { - assert.equal(sock, clientSocket); - } else { - clientSocket = sock; - } - }); - - req.on('response', function(res) { - var data = ''; - res.setEncoding('utf8'); - res.on('data', function(c) { - data += c; - }); - res.on('end', function() { - assert.equal(data, '/' + n); - setTimeout(function() { - actualRequests++; - makeRequest(n - 1); - }, 1); - }); - }); -} - -process.on('exit', function() { - assert.equal(actualRequests, expectRequests) - console.log('ok'); -}); diff --git a/test/simple/test-http-legacy.js b/test/simple/test-http-legacy.js deleted file mode 100644 index c6605b0e4..000000000 --- a/test/simple/test-http-legacy.js +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -function p(x) { - common.error(common.inspect(x)); -} - -var responses_sent = 0; -var responses_recvd = 0; -var body0 = ''; -var body1 = ''; - -var server = http.createServer(function(req, res) { - if (responses_sent == 0) { - assert.equal('GET', req.method); - assert.equal('/hello', url.parse(req.url).pathname); - - console.dir(req.headers); - assert.equal(true, 'accept' in req.headers); - assert.equal('*/*', req.headers['accept']); - - assert.equal(true, 'foo' in req.headers); - assert.equal('bar', req.headers['foo']); - } - - if (responses_sent == 1) { - assert.equal('POST', req.method); - assert.equal('/world', url.parse(req.url).pathname); - this.close(); - } - - req.on('end', function() { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('The path was ' + url.parse(req.url).pathname); - res.end(); - responses_sent += 1; - }); - req.resume(); - - //assert.equal('127.0.0.1', res.connection.remoteAddress); -}); - -server.listen(common.PORT, function() { - var client = http.createClient(common.PORT); - var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); - setTimeout(function() { - req.end(); - }, 100); - req.on('response', function(res) { - assert.equal(200, res.statusCode); - responses_recvd += 1; - res.setEncoding('utf8'); - res.on('data', function(chunk) { body0 += chunk; }); - common.debug('Got /hello response'); - }); - - setTimeout(function() { - var req = client.request('POST', '/world'); - req.end(); - req.on('response', function(res) { - assert.equal(200, res.statusCode); - responses_recvd += 1; - res.setEncoding('utf8'); - res.on('data', function(chunk) { body1 += chunk; }); - common.debug('Got /world response'); - }); - }, 1); -}); - -process.on('exit', function() { - common.debug('responses_recvd: ' + responses_recvd); - assert.equal(2, responses_recvd); - - common.debug('responses_sent: ' + responses_sent); - assert.equal(2, responses_sent); - - assert.equal('The path was /hello', body0); - assert.equal('The path was /world', body1); -}); diff --git a/test/simple/test-http-localaddress-bind-error.js b/test/simple/test-http-localaddress-bind-error.js deleted file mode 100644 index 719525cc6..000000000 --- a/test/simple/test-http-localaddress-bind-error.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var invalidLocalAddress = '1.2.3.4'; -var gotError = false; - -var server = http.createServer(function(req, res) { - console.log("Connect from: " + req.connection.remoteAddress); - - req.on('end', function() { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('You are from: ' + req.connection.remoteAddress); - }); - req.resume(); -}); - -server.listen(common.PORT, "127.0.0.1", function() { - var req = http.request({ - host: 'localhost', - port: common.PORT, - path: '/', - method: 'GET', - localAddress: invalidLocalAddress - }, function(res) { - assert.fail('unexpectedly got response from server'); - }).on('error', function(e) { - console.log('client got error: ' + e.message); - gotError = true; - server.close(); - }).end(); -}); - -process.on('exit', function() { - assert.ok(gotError); -}); diff --git a/test/simple/test-http-localaddress.js b/test/simple/test-http-localaddress.js deleted file mode 100644 index d5778e09b..000000000 --- a/test/simple/test-http-localaddress.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var http = require('http'), - assert = require('assert'); - -if (['linux', 'win32'].indexOf(process.platform) == -1) { - console.log('Skipping platform-specific test.'); - process.exit(); -} - -var server = http.createServer(function (req, res) { - console.log("Connect from: " + req.connection.remoteAddress); - assert.equal('127.0.0.2', req.connection.remoteAddress); - - req.on('end', function() { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('You are from: ' + req.connection.remoteAddress); - }); - req.resume(); -}); - -server.listen(common.PORT, "127.0.0.1", function() { - var options = { host: 'localhost', - port: common.PORT, - path: '/', - method: 'GET', - localAddress: '127.0.0.2' }; - - var req = http.request(options, function(res) { - res.on('end', function() { - server.close(); - process.exit(); - }); - res.resume(); - }); - req.end(); -}); diff --git a/test/simple/test-http-malformed-request.js b/test/simple/test-http-malformed-request.js deleted file mode 100644 index 52165a21d..000000000 --- a/test/simple/test-http-malformed-request.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); -var url = require('url'); - -// Make sure no exceptions are thrown when receiving malformed HTTP -// requests. - -var nrequests_completed = 0; -var nrequests_expected = 1; - -var server = http.createServer(function(req, res) { - console.log('req: ' + JSON.stringify(url.parse(req.url))); - - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('Hello World'); - res.end(); - - if (++nrequests_completed == nrequests_expected) server.close(); -}); -server.listen(common.PORT); - -server.on('listening', function() { - var c = net.createConnection(common.PORT); - c.on('connect', function() { - c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); - c.end(); - }); - - // TODO add more! -}); - -process.on('exit', function() { - assert.equal(nrequests_expected, nrequests_completed); -}); diff --git a/test/simple/test-http-many-ended-pipelines.js b/test/simple/test-http-many-ended-pipelines.js deleted file mode 100644 index dffde722f..000000000 --- a/test/simple/test-http-many-ended-pipelines.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// no warnings should happen! -var trace = console.trace; -console.trace = function() { - trace.apply(console, arguments); - throw new Error('no tracing should happen here'); -}; - -var http = require('http'); -var net = require('net'); - -var numRequests = 20; -var done = 0; - -var server = http.createServer(function(req, res) { - res.end('ok'); - - // Oh no! The connection died! - req.socket.destroy(); - if (++done == numRequests) - server.close(); -}); - -server.listen(common.PORT); - -var client = net.connect({ port: common.PORT, allowHalfOpen: true }); -for (var i = 0; i < numRequests; i++) { - client.write('GET / HTTP/1.1\r\n' + - 'Host: some.host.name\r\n'+ - '\r\n\r\n'); -} -client.end(); -client.pipe(process.stdout); diff --git a/test/simple/test-http-max-headers-count.js b/test/simple/test-http-max-headers-count.js deleted file mode 100644 index 4595b11e7..000000000 --- a/test/simple/test-http-max-headers-count.js +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var requests = 0; -var responses = 0; - -var headers = {}; -var N = 2000; -for (var i = 0; i < N; ++i) { - headers['key' + i] = i; -} - -var maxAndExpected = [ // for server - [50, 50], - [1500, 1500], - [0, N + 2] // Host and Connection -]; -var max = maxAndExpected[requests][0]; -var expected = maxAndExpected[requests][1]; - -var server = http.createServer(function(req, res) { - assert.equal(Object.keys(req.headers).length, expected); - if (++requests < maxAndExpected.length) { - max = maxAndExpected[requests][0]; - expected = maxAndExpected[requests][1]; - server.maxHeadersCount = max; - } - res.writeHead(200, headers); - res.end(); -}); -server.maxHeadersCount = max; - -server.listen(common.PORT, function() { - var maxAndExpected = [ // for client - [20, 20], - [1200, 1200], - [0, N + 3] // Connection, Date and Transfer-Encoding - ]; - doRequest(); - - function doRequest() { - var max = maxAndExpected[responses][0]; - var expected = maxAndExpected[responses][1]; - var req = http.request({ - port: common.PORT, - headers: headers - }, function(res) { - assert.equal(Object.keys(res.headers).length, expected); - res.on('end', function() { - if (++responses < maxAndExpected.length) { - doRequest(); - } else { - server.close(); - } - }); - res.resume(); - }); - req.maxHeadersCount = max; - req.end(); - } -}); - -process.on('exit', function() { - assert.equal(requests, maxAndExpected.length); - assert.equal(responses, maxAndExpected.length); -}); diff --git a/test/simple/test-http-methods.js b/test/simple/test-http-methods.js deleted file mode 100644 index eec66d280..000000000 --- a/test/simple/test-http-methods.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); - -assert(Array.isArray(http.METHODS)); -assert(http.METHODS.length > 0); -assert(http.METHODS.indexOf('GET') !== -1); -assert(http.METHODS.indexOf('HEAD') !== -1); -assert(http.METHODS.indexOf('POST') !== -1); -assert.deepEqual(util._extend([], http.METHODS), http.METHODS.sort()); diff --git a/test/simple/test-http-multi-line-headers.js b/test/simple/test-http-multi-line-headers.js deleted file mode 100644 index 9415abadc..000000000 --- a/test/simple/test-http-multi-line-headers.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var net = require('net'); - -var gotResponse = false; - -var server = net.createServer(function(conn) { - var body = 'Yet another node.js server.'; - - var response = - 'HTTP/1.1 200 OK\r\n' + - 'Connection: close\r\n' + - 'Content-Length: ' + body.length + '\r\n' + - 'Content-Type: text/plain;\r\n' + - ' x-unix-mode=0600;\r\n' + - ' name=\"hello.txt\"\r\n' + - '\r\n' + - body; - - conn.end(response); - server.close(); -}); - -server.listen(common.PORT, function() { - http.get({host: '127.0.0.1', port: common.PORT}, function(res) { - assert.equal(res.headers['content-type'], - 'text/plain; x-unix-mode=0600; name="hello.txt"'); - gotResponse = true; - res.destroy(); - }); -}); - -process.on('exit', function() { - assert.ok(gotResponse); -}); diff --git a/test/simple/test-http-mutable-headers.js b/test/simple/test-http-mutable-headers.js deleted file mode 100644 index 6106ac6ee..000000000 --- a/test/simple/test-http-mutable-headers.js +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -// Simple test of Node's HTTP Client mutable headers -// OutgoingMessage.prototype.setHeader(name, value) -// OutgoingMessage.prototype.getHeader(name) -// OutgoingMessage.prototype.removeHeader(name, value) -// ServerResponse.prototype.statusCode -// .method -// .path - -var testsComplete = 0; -var test = 'headers'; -var content = 'hello world\n'; -var cookies = [ - 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', - 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' -]; - -var s = http.createServer(function(req, res) { - switch (test) { - case 'headers': - assert.throws(function() { res.setHeader() }); - assert.throws(function() { res.setHeader('someHeader') }); - assert.throws(function() { res.getHeader() }); - assert.throws(function() { res.removeHeader() }); - - res.setHeader('x-test-header', 'testing'); - res.setHeader('X-TEST-HEADER2', 'testing'); - res.setHeader('set-cookie', cookies); - res.setHeader('x-test-array-header', [1, 2, 3]); - - var val1 = res.getHeader('x-test-header'); - var val2 = res.getHeader('x-test-header2'); - assert.equal(val1, 'testing'); - assert.equal(val2, 'testing'); - - res.removeHeader('x-test-header2'); - break; - - case 'contentLength': - res.setHeader('content-length', content.length); - assert.equal(content.length, res.getHeader('Content-Length')); - break; - - case 'transferEncoding': - res.setHeader('transfer-encoding', 'chunked'); - assert.equal(res.getHeader('Transfer-Encoding'), 'chunked'); - break; - - case 'writeHead': - res.statusCode = 404; - res.setHeader('x-foo', 'keyboard cat'); - res.writeHead(200, { 'x-foo': 'bar', 'x-bar': 'baz' }); - break; - } - - res.statusCode = 201; - res.end(content); -}); - -s.listen(common.PORT, nextTest); - - -function nextTest() { - if (test === 'end') { - return s.close(); - } - - var bufferedResponse = ''; - - http.get({ port: common.PORT }, function(response) { - console.log('TEST: ' + test); - console.log('STATUS: ' + response.statusCode); - console.log('HEADERS: '); - console.dir(response.headers); - - switch (test) { - case 'headers': - assert.equal(response.statusCode, 201); - assert.equal(response.headers['x-test-header'], - 'testing'); - assert.equal(response.headers['x-test-array-header'], - [1, 2, 3].join(', ')); - assert.deepEqual(cookies, - response.headers['set-cookie']); - assert.equal(response.headers['x-test-header2'] !== undefined, false); - // Make the next request - test = 'contentLength'; - console.log('foobar'); - break; - - case 'contentLength': - assert.equal(response.headers['content-length'], content.length); - test = 'transferEncoding'; - break; - - case 'transferEncoding': - assert.equal(response.headers['transfer-encoding'], 'chunked'); - test = 'writeHead'; - break; - - case 'writeHead': - assert.equal(response.headers['x-foo'], 'bar'); - assert.equal(response.headers['x-bar'], 'baz'); - assert.equal(200, response.statusCode); - test = 'end'; - break; - - default: - throw Error('?'); - } - - response.setEncoding('utf8'); - response.on('data', function(s) { - bufferedResponse += s; - }); - - response.on('end', function() { - assert.equal(content, bufferedResponse); - testsComplete++; - nextTest(); - }); - }); -} - - -process.on('exit', function() { - assert.equal(4, testsComplete); -}); - diff --git a/test/simple/test-http-no-content-length.js b/test/simple/test-http-no-content-length.js deleted file mode 100644 index 8c565aedc..000000000 --- a/test/simple/test-http-no-content-length.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); - -var body = ''; - -var server = net.createServer(function(socket) { - // Neither Content-Length nor Connection - socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); -}).listen(common.PORT, function() { - var req = http.get({port: common.PORT}, function(res) { - res.setEncoding('utf8'); - res.on('data', function(chunk) { - body += chunk; - }); - res.on('end', function() { - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(body, 'Hello'); -}); diff --git a/test/simple/test-http-outgoing-finish.js b/test/simple/test-http-outgoing-finish.js deleted file mode 100644 index 668040a81..000000000 --- a/test/simple/test-http-outgoing-finish.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -http.createServer(function(req, res) { - req.resume(); - req.on('end', function() { - write(res); - }); - this.close(); -}).listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - method: 'PUT' - }); - write(req); - req.on('response', function(res) { - res.resume(); - }); -}); - -var buf = new Buffer(1024 * 16); -buf.fill('x'); -function write(out) { - var name = out.constructor.name; - var finishEvent = false; - var endCb = false; - - // first, write until it gets some backpressure - while (out.write(buf)) {} - - // now end, and make sure that we don't get the 'finish' event - // before the tick where the cb gets called. We give it until - // nextTick because this is added as a listener before the endcb - // is registered. The order is not what we're testing here, just - // that 'finish' isn't emitted until the stream is fully flushed. - out.on('finish', function() { - finishEvent = true; - console.error('%s finish event', name); - process.nextTick(function() { - assert(endCb, name + ' got finish event before endcb!'); - console.log('ok - %s finishEvent', name); - }); - }); - - out.end(buf, function() { - endCb = true; - console.error('%s endCb', name); - process.nextTick(function() { - assert(finishEvent, name + ' got endCb event before finishEvent!'); - console.log('ok - %s endCb', name); - }); - }); -} diff --git a/test/simple/test-http-parser-bad-ref.js b/test/simple/test-http-parser-bad-ref.js deleted file mode 100644 index 0e2a77bb3..000000000 --- a/test/simple/test-http-parser-bad-ref.js +++ /dev/null @@ -1,86 +0,0 @@ -// Run this program with valgrind or efence with --expose_gc to expose the -// problem. - -// Flags: --expose_gc - -var common = require('../common'); -var assert = require('assert'); -var HTTPParser = process.binding('http_parser').HTTPParser; - -var kOnHeaders = HTTPParser.kOnHeaders | 0; -var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; -var kOnBody = HTTPParser.kOnBody | 0; -var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; - -var headersComplete = 0; -var messagesComplete = 0; - -function flushPool() { - new Buffer(Buffer.poolSize - 1); - gc(); -} - -function demoBug(part1, part2) { - flushPool(); - - var parser = new HTTPParser('REQUEST'); - - parser.headers = []; - parser.url = ''; - - parser[kOnHeaders] = function(headers, url) { - parser.headers = parser.headers.concat(headers); - parser.url += url; - }; - - parser[kOnHeadersComplete] = function(info) { - headersComplete++; - console.log('url', info.url); - }; - - parser[kOnBody] = function(b, start, len) { }; - - parser[kOnMessageComplete] = function() { - messagesComplete++; - }; - - - // We use a function to eliminate references to the Buffer b - // We want b to be GCed. The parser will hold a bad reference to it. - (function() { - var b = Buffer(part1); - flushPool(); - - console.log('parse the first part of the message'); - parser.execute(b, 0, b.length); - })(); - - flushPool(); - - (function() { - var b = Buffer(part2); - - console.log('parse the second part of the message'); - parser.execute(b, 0, b.length); - parser.finish(); - })(); - - flushPool(); -} - - -demoBug('POST /1', '/22 HTTP/1.1\r\n' + - 'Content-Type: text/plain\r\n' + - 'Content-Length: 4\r\n\r\n' + - 'pong'); - -demoBug('POST /1/22 HTTP/1.1\r\n' + - 'Content-Type: tex', 't/plain\r\n' + - 'Content-Length: 4\r\n\r\n' + - 'pong'); - -process.on('exit', function() { - assert.equal(2, headersComplete); - assert.equal(2, messagesComplete); - console.log('done!'); -}); diff --git a/test/simple/test-http-parser-free.js b/test/simple/test-http-parser-free.js deleted file mode 100644 index 7b35781f4..000000000 --- a/test/simple/test-http-parser-free.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var N = 100; -var responses = 0; - -var server = http.createServer(function(req, res) { - res.end('Hello'); -}); - -server.listen(common.PORT, function() { - http.globalAgent.maxSockets = 1; - var parser; - for (var i = 0; i < N; ++i) { - (function makeRequest(i) { - var req = http.get({port: common.PORT}, function(res) { - if (!parser) { - parser = req.parser; - } else { - assert.strictEqual(req.parser, parser); - } - - if (++responses === N) { - server.close(); - } - res.resume(); - }); - })(i); - } -}); - -process.on('exit', function() { - assert.equal(responses, N); -}); diff --git a/test/simple/test-http-parser.js b/test/simple/test-http-parser.js deleted file mode 100644 index c61dc9911..000000000 --- a/test/simple/test-http-parser.js +++ /dev/null @@ -1,570 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var HTTPParser = process.binding('http_parser').HTTPParser; - -var CRLF = '\r\n'; -var REQUEST = HTTPParser.REQUEST; -var RESPONSE = HTTPParser.RESPONSE; - -var methods = HTTPParser.methods; - -var kOnHeaders = HTTPParser.kOnHeaders | 0; -var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; -var kOnBody = HTTPParser.kOnBody | 0; -var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; - -// The purpose of this test is not to check HTTP compliance but to test the -// binding. Tests for pathological http messages should be submitted -// upstream to https://github.com/joyent/http-parser for inclusion into -// deps/http-parser/test.c - - -function newParser(type) { - var parser = new HTTPParser(type); - - parser.headers = []; - parser.url = ''; - - parser[kOnHeaders] = function(headers, url) { - parser.headers = parser.headers.concat(headers); - parser.url += url; - }; - - parser[kOnHeadersComplete] = function(info) { - }; - - parser[kOnBody] = function(b, start, len) { - assert.ok(false, 'Function should not be called.'); - }; - - parser[kOnMessageComplete] = function() { - }; - - return parser; -} - - -function mustCall(f, times) { - var actual = 0; - - process.setMaxListeners(256); - process.on('exit', function() { - assert.equal(actual, times || 1); - }); - - return function() { - actual++; - return f.apply(this, Array.prototype.slice.call(arguments)); - }; -} - - -function expectBody(expected) { - return mustCall(function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, expected); - }); -} - - -// -// Simple request test. -// -(function() { - var request = Buffer( - 'GET /hello HTTP/1.1' + CRLF + - CRLF); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('GET')); - assert.equal(info.url || parser.url, '/hello'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - }); - - parser.execute(request, 0, request.length); - - // - // Check that if we throw an error in the callbacks that error will be - // thrown from parser.execute() - // - - parser[kOnHeadersComplete] = function(info) { - throw new Error('hello world'); - }; - - parser.reinitialize(HTTPParser.REQUEST); - - assert.throws(function() { - parser.execute(request, 0, request.length); - }, Error, 'hello world'); -})(); - - -// -// Simple response test. -// -(function() { - var request = Buffer( - 'HTTP/1.1 200 OK' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Content-Length: 4' + CRLF + - CRLF + - 'pong'); - - var parser = newParser(RESPONSE); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, undefined); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - assert.equal(info.statusCode, 200); - assert.equal(info.statusMessage, "OK"); - }); - - parser[kOnBody] = mustCall(function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'pong'); - }); - - parser.execute(request, 0, request.length); -})(); - - -// -// Response with no headers. -// -(function() { - var request = Buffer( - 'HTTP/1.0 200 Connection established' + CRLF + - CRLF); - - var parser = newParser(RESPONSE); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, undefined); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 0); - assert.equal(info.statusCode, 200); - assert.equal(info.statusMessage, "Connection established"); - assert.deepEqual(info.headers || parser.headers, []); - }); - - parser.execute(request, 0, request.length); -})(); - - -// -// Trailing headers. -// -(function() { - var request = Buffer( - 'POST /it HTTP/1.1' + CRLF + - 'Transfer-Encoding: chunked' + CRLF + - CRLF + - '4' + CRLF + - 'ping' + CRLF + - '0' + CRLF + - 'Vary: *' + CRLF + - 'Content-Type: text/plain' + CRLF + - CRLF); - - var seen_body = false; - - function onHeaders(headers, url) { - assert.ok(seen_body); // trailers should come after the body - assert.deepEqual(headers, - ['Vary', '*', 'Content-Type', 'text/plain']); - } - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url || parser.url, '/it'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - // expect to see trailing headers now - parser[kOnHeaders] = mustCall(onHeaders); - }); - - parser[kOnBody] = mustCall(function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'ping'); - seen_body = true; - }); - - parser.execute(request, 0, request.length); -})(); - - -// -// Test header ordering. -// -(function() { - var request = Buffer( - 'GET / HTTP/1.0' + CRLF + - 'X-Filler: 1337' + CRLF + - 'X-Filler: 42' + CRLF + - 'X-Filler2: 42' + CRLF + - CRLF); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('GET')); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 0); - assert.deepEqual(info.headers || parser.headers, - ['X-Filler', '1337', - 'X-Filler', '42', - 'X-Filler2', '42']); - }); - - parser.execute(request, 0, request.length); -})(); - - -// -// Test large number of headers -// -(function() { - // 256 X-Filler headers - var lots_of_headers = 'X-Filler: 42' + CRLF; - for (var i = 0; i < 8; ++i) lots_of_headers += lots_of_headers; - - var request = Buffer( - 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + - lots_of_headers + - CRLF); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('GET')); - assert.equal(info.url || parser.url, '/foo/bar/baz?quux=42#1337'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 0); - - var headers = info.headers || parser.headers; - - assert.equal(headers.length, 2 * 256); // 256 key/value pairs - for (var i = 0; i < headers.length; i += 2) { - assert.equal(headers[i], 'X-Filler'); - assert.equal(headers[i + 1], '42'); - } - }); - - parser.execute(request, 0, request.length); -})(); - - -// -// Test request body -// -(function() { - var request = Buffer( - 'POST /it HTTP/1.1' + CRLF + - 'Content-Type: application/x-www-form-urlencoded' + CRLF + - 'Content-Length: 15' + CRLF + - CRLF + - 'foo=42&bar=1337'); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url || parser.url, '/it'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - }); - - parser[kOnBody] = mustCall(function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'foo=42&bar=1337'); - }); - - parser.execute(request, 0, request.length); -})(); - - -// -// Test chunked request body -// -(function() { - var request = Buffer( - 'POST /it HTTP/1.1' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Transfer-Encoding: chunked' + CRLF + - CRLF + - '3' + CRLF + - '123' + CRLF + - '6' + CRLF + - '123456' + CRLF + - 'A' + CRLF + - '1234567890' + CRLF + - '0' + CRLF); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url || parser.url, '/it'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - }); - - var body_part = 0, - body_parts = ['123', '123456', '1234567890']; - - function onBody(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, body_parts[body_part++]); - } - - parser[kOnBody] = mustCall(onBody, body_parts.length); - parser.execute(request, 0, request.length); -})(); - - -// -// Test chunked request body spread over multiple buffers (packets) -// -(function() { - var request = Buffer( - 'POST /it HTTP/1.1' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Transfer-Encoding: chunked' + CRLF + - CRLF + - '3' + CRLF + - '123' + CRLF + - '6' + CRLF + - '123456' + CRLF); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url || parser.url, '/it'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - }); - - var body_part = 0, - body_parts = [ - '123', '123456', '123456789', - '123456789ABC', '123456789ABCDEF']; - - function onBody(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, body_parts[body_part++]); - } - - parser[kOnBody] = mustCall(onBody, body_parts.length); - parser.execute(request, 0, request.length); - - request = Buffer( - '9' + CRLF + - '123456789' + CRLF + - 'C' + CRLF + - '123456789ABC' + CRLF + - 'F' + CRLF + - '123456789ABCDEF' + CRLF + - '0' + CRLF); - - parser.execute(request, 0, request.length); -})(); - - -// -// Stress test. -// -(function() { - var request = Buffer( - 'POST /helpme HTTP/1.1' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Transfer-Encoding: chunked' + CRLF + - CRLF + - '3' + CRLF + - '123' + CRLF + - '6' + CRLF + - '123456' + CRLF + - '9' + CRLF + - '123456789' + CRLF + - 'C' + CRLF + - '123456789ABC' + CRLF + - 'F' + CRLF + - '123456789ABCDEF' + CRLF + - '0' + CRLF); - - function test(a, b) { - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url || parser.url, '/helpme'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - }); - - var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; - - parser[kOnBody] = function(buf, start, len) { - var chunk = '' + buf.slice(start, start + len); - assert.equal(expected_body.indexOf(chunk), 0); - expected_body = expected_body.slice(chunk.length); - }; - - parser.execute(a, 0, a.length); - parser.execute(b, 0, b.length); - - assert.equal(expected_body, ''); - } - - for (var i = 1; i < request.length - 1; ++i) { - var a = request.slice(0, i); - console.error('request.slice(0, ' + i + ') = ', - JSON.stringify(a.toString())); - var b = request.slice(i); - console.error('request.slice(' + i + ') = ', - JSON.stringify(b.toString())); - test(a, b); - } -})(); - - -// -// Byte by byte test. -// -(function() { - var request = Buffer( - 'POST /it HTTP/1.1' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Transfer-Encoding: chunked' + CRLF + - CRLF + - '3' + CRLF + - '123' + CRLF + - '6' + CRLF + - '123456' + CRLF + - '9' + CRLF + - '123456789' + CRLF + - 'C' + CRLF + - '123456789ABC' + CRLF + - 'F' + CRLF + - '123456789ABCDEF' + CRLF + - '0' + CRLF); - - var parser = newParser(REQUEST); - - parser[kOnHeadersComplete] = mustCall(function(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url || parser.url, '/it'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - assert.deepEqual(info.headers || parser.headers, - ['Content-Type', 'text/plain', - 'Transfer-Encoding', 'chunked']); - }); - - var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; - - parser[kOnBody] = function(buf, start, len) { - var chunk = '' + buf.slice(start, start + len); - assert.equal(expected_body.indexOf(chunk), 0); - expected_body = expected_body.slice(chunk.length); - }; - - for (var i = 0; i < request.length; ++i) { - parser.execute(request, i, 1); - } - - assert.equal(expected_body, ''); -})(); - - -// -// Test parser reinit sequence. -// -(function() { - var req1 = Buffer( - 'PUT /this HTTP/1.1' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Transfer-Encoding: chunked' + CRLF + - CRLF + - '4' + CRLF + - 'ping' + CRLF + - '0' + CRLF); - - var req2 = Buffer( - 'POST /that HTTP/1.0' + CRLF + - 'Content-Type: text/plain' + CRLF + - 'Content-Length: 4' + CRLF + - CRLF + - 'pong'); - - function onHeadersComplete1(info) { - assert.equal(info.method, methods.indexOf('PUT')); - assert.equal(info.url, '/this'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 1); - assert.deepEqual(info.headers, - ['Content-Type', 'text/plain', - 'Transfer-Encoding', 'chunked']); - }; - - function onHeadersComplete2(info) { - assert.equal(info.method, methods.indexOf('POST')); - assert.equal(info.url, '/that'); - assert.equal(info.versionMajor, 1); - assert.equal(info.versionMinor, 0); - assert.deepEqual(info.headers, - ['Content-Type', 'text/plain', - 'Content-Length', '4']); - }; - - var parser = newParser(REQUEST); - parser[kOnHeadersComplete] = onHeadersComplete1; - parser[kOnBody] = expectBody('ping'); - parser.execute(req1, 0, req1.length); - - parser.reinitialize(REQUEST); - parser[kOnBody] = expectBody('pong'); - parser[kOnHeadersComplete] = onHeadersComplete2; - parser.execute(req2, 0, req2.length); -})(); - -// Test parser 'this' safety -// https://github.com/joyent/node/issues/6690 -assert.throws(function() { - var request = Buffer( - 'GET /hello HTTP/1.1' + CRLF + - CRLF); - - var parser = newParser(REQUEST); - var notparser = { execute: parser.execute }; - notparser.execute(request, 0, request.length); -}, TypeError); diff --git a/test/simple/test-http-pause-resume-one-end.js b/test/simple/test-http-pause-resume-one-end.js deleted file mode 100644 index f397452e9..000000000 --- a/test/simple/test-http-pause-resume-one-end.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.Server(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World\n'); - server.close(); -}); - - -var dataCount = 0, endCount = 0; - -server.listen(common.PORT, function() { - var opts = { - port: common.PORT, - headers: { connection: 'close' } - }; - - http.get(opts, function(res) { - res.on('data', function(chunk) { - dataCount++; - res.pause(); - setTimeout(function() { - res.resume(); - }); - }); - - res.on('end', function() { - endCount++; - }); - }); -}); - - -process.on('exit', function() { - assert.equal(1, dataCount); - assert.equal(1, endCount); -}); diff --git a/test/simple/test-http-pause.js b/test/simple/test-http-pause.js deleted file mode 100644 index 0edf6d622..000000000 --- a/test/simple/test-http-pause.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var expectedServer = 'Request Body from Client'; -var resultServer = ''; -var expectedClient = 'Response Body from Server'; -var resultClient = ''; - -var server = http.createServer(function(req, res) { - common.debug('pause server request'); - req.pause(); - setTimeout(function() { - common.debug('resume server request'); - req.resume(); - req.setEncoding('utf8'); - req.on('data', function(chunk) { - resultServer += chunk; - }); - req.on('end', function() { - common.debug(resultServer); - res.writeHead(200); - res.end(expectedClient); - }); - }, 100); -}); - -server.listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - path: '/', - method: 'POST' - }, function(res) { - common.debug('pause client response'); - res.pause(); - setTimeout(function() { - common.debug('resume client response'); - res.resume(); - res.on('data', function(chunk) { - resultClient += chunk; - }); - res.on('end', function() { - common.debug(resultClient); - server.close(); - }); - }, 100); - }); - req.end(expectedServer); -}); - -process.on('exit', function() { - assert.equal(expectedServer, resultServer); - assert.equal(expectedClient, resultClient); -}); diff --git a/test/simple/test-http-pipe-fs.js b/test/simple/test-http-pipe-fs.js deleted file mode 100644 index 57ebb11dc..000000000 --- a/test/simple/test-http-pipe-fs.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var fs = require('fs'); -var path = require('path'); - -var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); -var requests = 0; - -var server = http.createServer(function(req, res) { - ++requests; - var stream = fs.createWriteStream(file); - req.pipe(stream); - stream.on('close', function() { - res.writeHead(200); - res.end(); - }); -}).listen(common.PORT, function() { - http.globalAgent.maxSockets = 1; - - for (var i = 0; i < 2; ++i) { - (function(i) { - var req = http.request({ - port: common.PORT, - method: 'POST', - headers: { - 'Content-Length': 5 - } - }, function(res) { - res.on('end', function() { - common.debug('res' + i + ' end'); - if (i === 2) { - server.close(); - } - }); - res.resume(); - }); - req.on('socket', function(s) { - common.debug('req' + i + ' start'); - }); - req.end('12345'); - }(i + 1)); - } -}); - -process.on('exit', function() { - assert.equal(requests, 2); -}); diff --git a/test/simple/test-http-pipeline-flood.js b/test/simple/test-http-pipeline-flood.js deleted file mode 100644 index 64c56dbf3..000000000 --- a/test/simple/test-http-pipeline-flood.js +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -switch (process.argv[2]) { - case undefined: - return parent(); - case 'child': - return child(); - default: - throw new Error('wtf'); -} - -function parent() { - var http = require('http'); - var bigResponse = new Buffer(10240).fill('x'); - var gotTimeout = false; - var childClosed = false; - var requests = 0; - var connections = 0; - - var server = http.createServer(function(req, res) { - requests++; - res.setHeader('content-length', bigResponse.length); - res.end(bigResponse); - }); - - server.on('connection', function(conn) { - connections++; - }); - - // kill the connection after a bit, verifying that the - // flood of requests was eventually halted. - server.setTimeout(200, function(conn) { - gotTimeout = true; - conn.destroy(); - }); - - server.listen(common.PORT, function() { - var spawn = require('child_process').spawn; - var args = [__filename, 'child']; - var child = spawn(process.execPath, args, { stdio: 'inherit' }); - child.on('close', function(code) { - assert(!code); - childClosed = true; - server.close(); - }); - }); - - process.on('exit', function() { - assert(gotTimeout); - assert(childClosed); - assert.equal(connections, 1); - // The number of requests we end up processing before the outgoing - // connection backs up and requires a drain is implementation-dependent. - // We can safely assume is more than 250. - console.log('server got %d requests', requests); - assert(requests >= 250); - console.log('ok'); - }); -} - -function child() { - var net = require('net'); - - var gotEpipe = false; - var conn = net.connect({ port: common.PORT }); - - var req = 'GET / HTTP/1.1\r\nHost: localhost:' + - common.PORT + '\r\nAccept: */*\r\n\r\n'; - - req = new Array(10241).join(req); - - conn.on('connect', function() { - write(); - }); - - conn.on('drain', write); - - conn.on('error', function(er) { - gotEpipe = true; - }); - - process.on('exit', function() { - assert(gotEpipe); - console.log('ok - child'); - }); - - function write() { - while (false !== conn.write(req, 'ascii')); - } -} diff --git a/test/simple/test-http-proxy.js b/test/simple/test-http-proxy.js deleted file mode 100644 index b531f1a8a..000000000 --- a/test/simple/test-http-proxy.js +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -var PROXY_PORT = common.PORT; -var BACKEND_PORT = common.PORT + 1; - -var cookies = [ - 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', - 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' -]; - -var headers = {'content-type': 'text/plain', - 'set-cookie': cookies, - 'hello': 'world' }; - -var backend = http.createServer(function(req, res) { - console.error('backend request'); - res.writeHead(200, headers); - res.write('hello world\n'); - res.end(); -}); - -var proxy = http.createServer(function(req, res) { - console.error('proxy req headers: ' + JSON.stringify(req.headers)); - var proxy_req = http.get({ - port: BACKEND_PORT, - path: url.parse(req.url).pathname - }, function(proxy_res) { - - console.error('proxy res headers: ' + JSON.stringify(proxy_res.headers)); - - assert.equal('world', proxy_res.headers['hello']); - assert.equal('text/plain', proxy_res.headers['content-type']); - assert.deepEqual(cookies, proxy_res.headers['set-cookie']); - - res.writeHead(proxy_res.statusCode, proxy_res.headers); - - proxy_res.on('data', function(chunk) { - res.write(chunk); - }); - - proxy_res.on('end', function() { - res.end(); - console.error('proxy res'); - }); - }); -}); - -var body = ''; - -var nlistening = 0; -function startReq() { - nlistening++; - if (nlistening < 2) return; - - var client = http.get({ - port: PROXY_PORT, - path: '/test' - }, function(res) { - console.error('got res'); - assert.equal(200, res.statusCode); - - assert.equal('world', res.headers['hello']); - assert.equal('text/plain', res.headers['content-type']); - assert.deepEqual(cookies, res.headers['set-cookie']); - - res.setEncoding('utf8'); - res.on('data', function(chunk) { body += chunk; }); - res.on('end', function() { - proxy.close(); - backend.close(); - console.error('closed both'); - }); - }); - console.error('client req'); -} - -console.error('listen proxy'); -proxy.listen(PROXY_PORT, startReq); - -console.error('listen backend'); -backend.listen(BACKEND_PORT, startReq); - -process.on('exit', function() { - assert.equal(body, 'hello world\n'); -}); diff --git a/test/simple/test-http-raw-headers.js b/test/simple/test-http-raw-headers.js deleted file mode 100644 index 0d31d8f61..000000000 --- a/test/simple/test-http-raw-headers.js +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -http.createServer(function(req, res) { - this.close(); - var expectRawHeaders = [ - 'Host', - 'localhost:' + common.PORT, - 'transfer-ENCODING', - 'CHUNKED', - 'x-BaR', - 'yoyoyo', - 'Connection', - 'close' - ]; - var expectHeaders = { - host: 'localhost:' + common.PORT, - 'transfer-encoding': 'CHUNKED', - 'x-bar': 'yoyoyo', - connection: 'close' - }; - - var expectRawTrailers = [ - 'x-bAr', - 'yOyOyOy', - 'x-baR', - 'OyOyOyO', - 'X-bAr', - 'yOyOyOy', - 'X-baR', - 'OyOyOyO' - ]; - - var expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; - - assert.deepEqual(req.rawHeaders, expectRawHeaders); - assert.deepEqual(req.headers, expectHeaders); - - req.on('end', function() { - assert.deepEqual(req.rawTrailers, expectRawTrailers); - assert.deepEqual(req.trailers, expectTrailers); - }); - - req.resume(); - res.addTrailers([ - ['x-fOo', 'xOxOxOx'], - ['x-foO', 'OxOxOxO'], - ['X-fOo', 'xOxOxOx'], - ['X-foO', 'OxOxOxO'] - ]); - res.end('x f o o'); -}).listen(common.PORT, function() { - var expectRawHeaders = [ - 'Date', - 'Tue, 06 Aug 2013 01:31:54 GMT', - 'Connection', - 'close', - 'Transfer-Encoding', - 'chunked' - ]; - var req = http.request({ port: common.PORT, path: '/' }); - req.addTrailers([ - ['x-bAr', 'yOyOyOy'], - ['x-baR', 'OyOyOyO'], - ['X-bAr', 'yOyOyOy'], - ['X-baR', 'OyOyOyO'] - ]); - req.setHeader('transfer-ENCODING', 'CHUNKED'); - req.setHeader('x-BaR', 'yoyoyo'); - req.end('y b a r'); - req.on('response', function(res) { - var expectRawHeaders = [ - 'Date', - null, - 'Connection', - 'close', - 'Transfer-Encoding', - 'chunked' - ]; - var expectHeaders = { - date: null, - connection: 'close', - 'transfer-encoding': 'chunked' - }; - res.rawHeaders[1] = null; - res.headers.date = null; - assert.deepEqual(res.rawHeaders, expectRawHeaders); - assert.deepEqual(res.headers, expectHeaders); - res.on('end', function() { - var expectRawTrailers = [ - 'x-fOo', - 'xOxOxOx', - 'x-foO', - 'OxOxOxO', - 'X-fOo', - 'xOxOxOx', - 'X-foO', - 'OxOxOxO' - ]; - var expectTrailers = { 'x-foo': 'xOxOxOx, OxOxOxO, xOxOxOx, OxOxOxO' }; - - assert.deepEqual(res.rawTrailers, expectRawTrailers); - assert.deepEqual(res.trailers, expectTrailers); - console.log('ok'); - }); - res.resume(); - }); -}); diff --git a/test/simple/test-http-remove-header-stays-removed.js b/test/simple/test-http-remove-header-stays-removed.js deleted file mode 100644 index a15c7750c..000000000 --- a/test/simple/test-http-remove-header-stays-removed.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var server = http.createServer(function(request, response) { - // removed headers should stay removed, even if node automatically adds them - // to the output: - response.removeHeader('connection'); - response.removeHeader('transfer-encoding'); - - // make sure that removing and then setting still works: - response.removeHeader('date'); - response.setHeader('date', 'coffee o clock'); - - response.end('beep boop\n'); - - this.close(); -}); - -var response = ''; - -process.on('exit', function() { - assert.equal('beep boop\n', response); - console.log('ok'); -}); - -server.listen(common.PORT, function() { - http.get({ port: common.PORT }, function(res) { - assert.equal(200, res.statusCode); - assert.deepEqual(res.headers, { date : 'coffee o clock' }); - - res.setEncoding('ascii'); - res.on('data', function(chunk) { - response += chunk; - }); - }); -}); diff --git a/test/simple/test-http-request-end-twice.js b/test/simple/test-http-request-end-twice.js deleted file mode 100644 index aa5877222..000000000 --- a/test/simple/test-http-request-end-twice.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.Server(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('hello world\n'); -}); -server.listen(common.PORT, function() { - var req = http.get({port: common.PORT}, function(res) { - res.on('end', function() { - assert.ok(!req.end()); - server.close(); - }); - res.resume(); - }); -}); - diff --git a/test/simple/test-http-request-end.js b/test/simple/test-http-request-end.js deleted file mode 100644 index f64dcc305..000000000 --- a/test/simple/test-http-request-end.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var expected = 'Post Body For Test'; -var result = ''; - -var server = http.Server(function(req, res) { - req.setEncoding('utf8'); - req.on('data', function(chunk) { - result += chunk; - }); - - req.on('end', function() { - server.close(); - }); - - res.writeHead(200); - res.end('hello world\n'); -}); - -server.listen(common.PORT, function() { - http.request({ - port: common.PORT, - path: '/', - method: 'POST' - }, function(res) { - console.log(res.statusCode); - res.resume(); - }).on('error', function(e) { - console.log(e.message); - process.exit(1); - }).end(expected); -}); - -process.on('exit', function() { - assert.equal(expected, result); -}); diff --git a/test/simple/test-http-request-methods.js b/test/simple/test-http-request-methods.js deleted file mode 100644 index 33575aed7..000000000 --- a/test/simple/test-http-request-methods.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); - -// Test that the DELETE, PATCH and PURGE verbs get passed through correctly - -['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { - var port = common.PORT + index; - - var server_response = ''; - var received_method = null; - - var server = http.createServer(function(req, res) { - received_method = req.method; - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello '); - res.write('world\n'); - res.end(); - }); - server.listen(port); - - server.on('listening', function() { - var c = net.createConnection(port); - - c.setEncoding('utf8'); - - c.on('connect', function() { - c.write(method + ' / HTTP/1.0\r\n\r\n'); - }); - - c.on('data', function(chunk) { - console.log(chunk); - server_response += chunk; - }); - - c.on('end', function() { - c.end(); - }); - - c.on('close', function() { - server.close(); - }); - }); - - process.on('exit', function() { - var m = server_response.split('\r\n\r\n'); - assert.equal(m[1], 'hello world\n'); - assert.equal(received_method, method); - }); -}); diff --git a/test/simple/test-http-res-write-after-end.js b/test/simple/test-http-res-write-after-end.js deleted file mode 100644 index 71a2564bf..000000000 --- a/test/simple/test-http-res-write-after-end.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var responseError; - -var server = http.Server(function(req, res) { - res.on('error', function onResError(err) { - responseError = err; - }); - - res.write('This should write.'); - res.end(); - - var r = res.write('This should raise an error.'); - assert.equal(r, true, 'write after end should return true'); -}); - -server.listen(common.PORT, function() { - var req = http.get({port: common.PORT}, function(res) { - server.close(); - }); -}); - -process.on('exit', function onProcessExit(code) { - assert(responseError, 'response should have emitted error'); - assert.equal(responseError.message, 'write after end'); -}); diff --git a/test/simple/test-http-res-write-end-dont-take-array.js b/test/simple/test-http-res-write-end-dont-take-array.js deleted file mode 100644 index d60b75552..000000000 --- a/test/simple/test-http-res-write-end-dont-take-array.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var test = 1; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - if (test === 1) { - // write should accept string - res.write('string'); - // write should accept buffer - res.write(new Buffer('asdf')); - - // write should not accept an Array - assert.throws(function() { - res.write(['array']); - }, TypeError, 'first argument must be a string or Buffer'); - - // end should not accept an Array - assert.throws(function() { - res.end(['moo']); - }, TypeError, 'first argument must be a string or Buffer'); - - // end should accept string - res.end('string'); - } else if (test === 2) { - // end should accept Buffer - res.end(new Buffer('asdf')); - } -}); - -server.listen(common.PORT, function() { - // just make a request, other tests handle responses - http.get({port: common.PORT}, function(res) { - res.resume(); - // lazy serial test, because we can only call end once per request - test += 1; - // do it again to test .end(Buffer); - http.get({port: common.PORT}, function(res) { - res.resume(); - server.close(); - }); - }); -}); diff --git a/test/simple/test-http-response-close.js b/test/simple/test-http-response-close.js deleted file mode 100644 index be89682a6..000000000 --- a/test/simple/test-http-response-close.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var requestGotEnd = false; -var responseGotEnd = false; - -var server = http.createServer(function(req, res) { - res.writeHead(200); - res.write('a'); - - req.on('close', function() { - console.error('request aborted'); - requestGotEnd = true; - }); - res.on('close', function() { - console.error('response aborted'); - responseGotEnd = true; - }); -}); -server.listen(common.PORT); - -server.on('listening', function() { - console.error('make req'); - http.get({ - port: common.PORT - }, function(res) { - console.error('got res'); - res.on('data', function(data) { - console.error('destroy res'); - res.destroy(); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.ok(requestGotEnd); - assert.ok(responseGotEnd); -}); diff --git a/test/simple/test-http-response-no-headers.js b/test/simple/test-http-response-no-headers.js deleted file mode 100644 index d16d8a4ce..000000000 --- a/test/simple/test-http-response-no-headers.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var expected = { - '0.9': 'I AM THE WALRUS', - '1.0': 'I AM THE WALRUS', - '1.1': '' -}; - -var gotExpected = false; - -function test(httpVersion, callback) { - process.on('exit', function() { - assert(gotExpected); - }); - - var server = net.createServer(function(conn) { - var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + - expected[httpVersion]; - - conn.end(reply); - }); - - server.listen(common.PORT, '127.0.0.1', function() { - var options = { - host: '127.0.0.1', - port: common.PORT - }; - - var req = http.get(options, function(res) { - var body = ''; - - res.on('data', function(data) { - body += data; - }); - - res.on('end', function() { - assert.equal(body, expected[httpVersion]); - gotExpected = true; - server.close(); - if (callback) process.nextTick(callback); - }); - }); - - req.on('error', function(err) { - throw err; - }); - }); -} - -test('0.9', function() { - test('1.0', function() { - test('1.1'); - }); -}); diff --git a/test/simple/test-http-response-readable.js b/test/simple/test-http-response-readable.js deleted file mode 100644 index b48c06fb4..000000000 --- a/test/simple/test-http-response-readable.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var testServer = new http.Server(function(req, res) { - res.writeHead(200); - res.end('Hello world'); -}); - -testServer.listen(common.PORT, function() { - http.get({ port: common.PORT }, function(res) { - assert.equal(res.readable, true, 'res.readable initially true'); - res.on('end', function() { - assert.equal(res.readable, false, 'res.readable set to false after end'); - testServer.close(); - }); - res.resume(); - }); -}); - diff --git a/test/simple/test-http-response-status-message.js b/test/simple/test-http-response-status-message.js deleted file mode 100644 index 3b3911010..000000000 --- a/test/simple/test-http-response-status-message.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var testsComplete = 0; - -var testCases = [ - { path: "/200", statusMessage: "OK", response: 'HTTP/1.1 200 OK\r\n\r\n' }, - { path: "/500", statusMessage: "Internal Server Error", response: 'HTTP/1.1 500 Internal Server Error\r\n\r\n' }, - { path: "/302", statusMessage: "Moved Temporarily", response: 'HTTP/1.1 302 Moved Temporarily\r\n\r\n' }, - { path: "/missing", statusMessage: "", response: 'HTTP/1.1 200 \r\n\r\n' }, - { path: "/missing-no-space", statusMessage: "", response: 'HTTP/1.1 200\r\n\r\n' } -]; -testCases.findByPath = function(path) { - var matching = this.filter(function(testCase) { return testCase.path === path; }); - if (matching.length === 0) { throw "failed to find test case with path " + path; } - return matching[0]; -}; - -var server = net.createServer(function(connection) { - connection.on('data', function(data) { - var path = data.toString().match(/GET (.*) HTTP.1.1/)[1]; - var testCase = testCases.findByPath(path); - - connection.write(testCase.response); - connection.end(); - }); -}); - -var runTest = function(testCaseIndex) { - var testCase = testCases[testCaseIndex]; - - http.get({ port: common.PORT, path: testCase.path }, function(response) { - console.log('client: expected status message: ' + testCase.statusMessage); - console.log('client: actual status message: ' + response.statusMessage); - assert.equal(testCase.statusMessage, response.statusMessage); - - response.on('end', function() { - testsComplete++; - - if (testCaseIndex + 1 < testCases.length) { - runTest(testCaseIndex + 1); - } else { - server.close(); - } - }); - - response.resume(); - }); -}; - -server.listen(common.PORT, function() { runTest(0); }); - -process.on('exit', function() { - assert.equal(testCases.length, testsComplete); -}); diff --git a/test/simple/test-http-server-multiheaders.js b/test/simple/test-http-server-multiheaders.js deleted file mode 100644 index b287169bd..000000000 --- a/test/simple/test-http-server-multiheaders.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Verify that the HTTP server implementation handles multiple instances -// of the same header as per RFC2616: joining the handful of fields by ', ' -// that support it, and dropping duplicates for other fields. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var srv = http.createServer(function(req, res) { - assert.equal(req.headers.accept, 'abc, def, ghijklmnopqrst'); - assert.equal(req.headers.host, 'foo'); - assert.equal(req.headers['www-authenticate'], 'foo, bar, baz'); - assert.equal(req.headers['proxy-authenticate'], 'foo, bar, baz'); - assert.equal(req.headers['x-foo'], 'bingo'); - assert.equal(req.headers['x-bar'], 'banjo, bango'); - assert.equal(req.headers['sec-websocket-protocol'], 'chat, share'); - assert.equal(req.headers['sec-websocket-extensions'], 'foo; 1, bar; 2, baz'); - - res.writeHead(200, {'Content-Type' : 'text/plain'}); - res.end('EOF'); - - srv.close(); -}); - -srv.listen(common.PORT, function() { - http.get({ - host: 'localhost', - port: common.PORT, - path: '/', - headers: [ - ['accept', 'abc'], - ['accept', 'def'], - ['Accept', 'ghijklmnopqrst'], - ['host', 'foo'], - ['Host', 'bar'], - ['hOst', 'baz'], - ['www-authenticate', 'foo'], - ['WWW-Authenticate', 'bar'], - ['WWW-AUTHENTICATE', 'baz'], - ['proxy-authenticate','foo'], - ['Proxy-Authenticate','bar'], - ['PROXY-AUTHENTICATE','baz'], - ['x-foo', 'bingo'], - ['x-bar', 'banjo'], - ['x-bar', 'bango'], - ['sec-websocket-protocol', 'chat'], - ['sec-websocket-protocol', 'share'], - ['sec-websocket-extensions', 'foo; 1'], - ['sec-websocket-extensions', 'bar; 2'], - ['sec-websocket-extensions', 'baz'] - ] - }); -}); diff --git a/test/simple/test-http-server-multiheaders2.js b/test/simple/test-http-server-multiheaders2.js deleted file mode 100644 index 40674c0fc..000000000 --- a/test/simple/test-http-server-multiheaders2.js +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Verify that the HTTP server implementation handles multiple instances -// of the same header as per RFC2616: joining the handful of fields by ', ' -// that support it, and dropping duplicates for other fields. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var multipleAllowed = [ - 'Accept', - 'Accept-Charset', - 'Accept-Encoding', - 'Accept-Language', - 'Connection', - 'Cookie', - 'DAV', // GH-2750 - 'Pragma', // GH-715 - 'Link', // GH-1187 - 'WWW-Authenticate', // GH-1083 - 'Proxy-Authenticate', // GH-4052 - 'Sec-Websocket-Extensions', // GH-2764 - 'Sec-Websocket-Protocol', // GH-2764 - 'Via', // GH-6660 - - // not a special case, just making sure it's parsed correctly - 'X-Forwarded-For', - - // make sure that unspecified headers is treated as multiple - 'Some-Random-Header', - 'X-Some-Random-Header', -]; - -var multipleForbidden = [ - 'Content-Type', - 'User-Agent', - 'Referer', - 'Host', - 'Authorization', - 'Proxy-Authorization', - 'If-Modified-Since', - 'If-Unmodified-Since', - 'From', - 'Location', - 'Max-Forwards', - - // special case, tested differently - //'Content-Length', -]; - -var srv = http.createServer(function(req, res) { - multipleForbidden.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header); - }); - multipleAllowed.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], 'foo, bar', 'header parsed incorrectly: ' + header); - }); - assert.equal(req.headers['content-length'], 0); - - res.writeHead(200, {'Content-Type' : 'text/plain'}); - res.end('EOF'); - - srv.close(); -}); - -function makeHeader(value) { - return function(header) { - return [header, value]; - } -} - -var headers = [] - .concat(multipleAllowed.map(makeHeader('foo'))) - .concat(multipleForbidden.map(makeHeader('foo'))) - .concat(multipleAllowed.map(makeHeader('bar'))) - .concat(multipleForbidden.map(makeHeader('bar'))) - // content-length is a special case since node.js - // is dropping connetions with non-numeric headers - .concat([['content-length', 0], ['content-length', 123]]); - -srv.listen(common.PORT, function() { - http.get({ - host: 'localhost', - port: common.PORT, - path: '/', - headers: headers, - }); -}); diff --git a/test/simple/test-http-server-stale-close.js b/test/simple/test-http-server-stale-close.js deleted file mode 100644 index aa42a049b..000000000 --- a/test/simple/test-http-server-stale-close.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var util = require('util'); -var fork = require('child_process').fork; - -if (process.env.NODE_TEST_FORK) { - var req = http.request({ - headers: {'Content-Length': '42'}, - method: 'POST', - host: '127.0.0.1', - port: common.PORT, - }, process.exit); - req.write('BAM'); - req.end(); -} -else { - var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': '42'}); - req.pipe(res); - req.on('close', function() { - server.close(); - res.end(); - }); - }); - server.listen(common.PORT, function() { - fork(__filename, { - env: util._extend(process.env, {NODE_TEST_FORK: '1'}) - }); - }); -} diff --git a/test/simple/test-http-server.js b/test/simple/test-http-server.js deleted file mode 100644 index 7d97382d3..000000000 --- a/test/simple/test-http-server.js +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); -var url = require('url'); -var qs = require('querystring'); - -var request_number = 0; -var requests_sent = 0; -var server_response = ''; -var client_got_eof = false; - -var server = http.createServer(function(req, res) { - res.id = request_number; - req.id = request_number++; - - if (req.id == 0) { - assert.equal('GET', req.method); - assert.equal('/hello', url.parse(req.url).pathname); - assert.equal('world', qs.parse(url.parse(req.url).query).hello); - assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo); - } - - if (req.id == 1) { - common.error('req 1'); - assert.equal('POST', req.method); - assert.equal('/quit', url.parse(req.url).pathname); - } - - if (req.id == 2) { - common.error('req 2'); - assert.equal('foo', req.headers['x-x']); - } - - if (req.id == 3) { - common.error('req 3'); - assert.equal('bar', req.headers['x-x']); - this.close(); - common.error('server closed'); - } - - setTimeout(function() { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write(url.parse(req.url).pathname); - res.end(); - }, 1); - -}); -server.listen(common.PORT); - -server.httpAllowHalfOpen = true; - -server.on('listening', function() { - var c = net.createConnection(common.PORT); - - c.setEncoding('utf8'); - - c.on('connect', function() { - c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n'); - requests_sent += 1; - }); - - c.on('data', function(chunk) { - server_response += chunk; - - if (requests_sent == 1) { - c.write('POST /quit HTTP/1.1\r\n\r\n'); - requests_sent += 1; - } - - if (requests_sent == 2) { - c.write('GET / HTTP/1.1\r\nX-X: foo\r\n\r\n' + - 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n'); - // Note: we are making the connection half-closed here - // before we've gotten the response from the server. This - // is a pretty bad thing to do and not really supported - // by many http servers. Node supports it optionally if - // you set server.httpAllowHalfOpen=true, which we've done - // above. - c.end(); - assert.equal(c.readyState, 'readOnly'); - requests_sent += 2; - } - - }); - - c.on('end', function() { - client_got_eof = true; - }); - - c.on('close', function() { - assert.equal(c.readyState, 'closed'); - }); -}); - -process.on('exit', function() { - assert.equal(4, request_number); - assert.equal(4, requests_sent); - - var hello = new RegExp('/hello'); - assert.equal(true, hello.exec(server_response) != null); - - var quit = new RegExp('/quit'); - assert.equal(true, quit.exec(server_response) != null); - - assert.equal(true, client_got_eof); -}); diff --git a/test/simple/test-http-set-cookies.js b/test/simple/test-http-set-cookies.js deleted file mode 100644 index bff34d829..000000000 --- a/test/simple/test-http-set-cookies.js +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var nresponses = 0; - -var server = http.createServer(function(req, res) { - if (req.url == '/one') { - res.writeHead(200, [['set-cookie', 'A'], - ['content-type', 'text/plain']]); - res.end('one\n'); - } else { - res.writeHead(200, [['set-cookie', 'A'], - ['set-cookie', 'B'], - ['content-type', 'text/plain']]); - res.end('two\n'); - } -}); -server.listen(common.PORT); - -server.on('listening', function() { - // - // one set-cookie header - // - http.get({ port: common.PORT, path: '/one' }, function(res) { - // set-cookie headers are always return in an array. - // even if there is only one. - assert.deepEqual(['A'], res.headers['set-cookie']); - assert.equal('text/plain', res.headers['content-type']); - - res.on('data', function(chunk) { - console.log(chunk.toString()); - }); - - res.on('end', function() { - if (++nresponses == 2) { - server.close(); - } - }); - }); - - // two set-cookie headers - - http.get({ port: common.PORT, path: '/two' }, function(res) { - assert.deepEqual(['A', 'B'], res.headers['set-cookie']); - assert.equal('text/plain', res.headers['content-type']); - - res.on('data', function(chunk) { - console.log(chunk.toString()); - }); - - res.on('end', function() { - if (++nresponses == 2) { - server.close(); - } - }); - }); - -}); - -process.on('exit', function() { - assert.equal(2, nresponses); -}); diff --git a/test/simple/test-http-set-timeout-server.js b/test/simple/test-http-set-timeout-server.js deleted file mode 100644 index ff4144963..000000000 --- a/test/simple/test-http-set-timeout-server.js +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var tests = []; - -function test(fn) { - if (!tests.length) - process.nextTick(run); - tests.push(fn); -} - -function run() { - var fn = tests.shift(); - if (fn) { - console.log('# %s', fn.name); - fn(run); - } else - console.log('ok'); -} - -test(function serverTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = http.createServer(function(req, res) { - // just do nothing, we should get a timeout event. - }); - server.listen(common.PORT); - server.setTimeout(50, function(socket) { - caughtTimeout = true; - socket.destroy(); - server.close(); - cb(); - }); - http.get({ port: common.PORT }).on('error', function() {}); -}); - -test(function serverRequestTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = http.createServer(function(req, res) { - // just do nothing, we should get a timeout event. - req.setTimeout(50, function() { - caughtTimeout = true; - req.socket.destroy(); - server.close(); - cb(); - }); - }); - server.listen(common.PORT); - var req = http.request({ port: common.PORT, method: 'POST' }); - req.on('error', function() {}); - req.write('Hello'); - // req is in progress -}); - -test(function serverResponseTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = http.createServer(function(req, res) { - // just do nothing, we should get a timeout event. - res.setTimeout(50, function() { - caughtTimeout = true; - res.socket.destroy(); - server.close(); - cb(); - }); - }); - server.listen(common.PORT); - http.get({ port: common.PORT }).on('error', function() {}); -}); - -test(function serverRequestNotTimeoutAfterEnd(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(caughtTimeoutOnResponse); - }); - var server = http.createServer(function(req, res) { - // just do nothing, we should get a timeout event. - req.setTimeout(50, function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); - }); - server.on('timeout', function(socket) { - socket.destroy(); - server.close(); - cb(); - }); - server.listen(common.PORT); - http.get({ port: common.PORT }).on('error', function() {}); -}); - -test(function serverResponseTimeoutWithPipeline(cb) { - var caughtTimeout = ''; - process.on('exit', function() { - assert.equal(caughtTimeout, '/2'); - }); - var server = http.createServer(function(req, res) { - res.setTimeout(50, function() { - caughtTimeout += req.url; - }); - if (req.url === '/1') res.end(); - }); - server.on('timeout', function(socket) { - socket.destroy(); - server.close(); - cb(); - }); - server.listen(common.PORT); - var c = net.connect({ port: common.PORT, allowHalfOpen: true }, function() { - c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - }); -}); - -test(function idleTimeout(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - var caughtTimeoutOnServer = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(!caughtTimeoutOnResponse); - assert(caughtTimeoutOnServer); - }); - var server = http.createServer(function(req, res) { - req.on('timeout', function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); - res.end(); - }); - server.setTimeout(50, function(socket) { - caughtTimeoutOnServer = true; - socket.destroy(); - server.close(); - cb(); - }); - server.listen(common.PORT); - var c = net.connect({ port: common.PORT, allowHalfOpen: true }, function() { - c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - // Keep-Alive - }); -}); diff --git a/test/simple/test-http-set-timeout.js b/test/simple/test-http-set-timeout.js deleted file mode 100644 index 01d182b34..000000000 --- a/test/simple/test-http-set-timeout.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.createServer(function(req, res) { - console.log('got request. setting 1 second timeout'); - req.connection.setTimeout(500); - - req.connection.on('timeout', function() { - req.connection.destroy(); - common.debug('TIMEOUT'); - server.close(); - }); -}); - -server.listen(common.PORT, function() { - console.log('Server running at http://127.0.0.1:' + common.PORT + '/'); - - var errorTimer = setTimeout(function() { - throw new Error('Timeout was not successful'); - }, 2000); - - var x = http.get({port: common.PORT, path: '/'}); - x.on('error', function() { - clearTimeout(errorTimer); - console.log('HTTP REQUEST COMPLETE (this is good)'); - }); - x.end(); - -}); diff --git a/test/simple/test-http-set-trailers.js b/test/simple/test-http-set-trailers.js deleted file mode 100644 index 445a3eeaa..000000000 --- a/test/simple/test-http-set-trailers.js +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var outstanding_reqs = 0; - -var server = http.createServer(function(req, res) { - res.writeHead(200, [['content-type', 'text/plain']]); - res.addTrailers({'x-foo': 'bar'}); - res.end('stuff' + '\n'); -}); -server.listen(common.PORT); - - -// first, we test an HTTP/1.0 request. -server.on('listening', function() { - var c = net.createConnection(common.PORT); - var res_buffer = ''; - - c.setEncoding('utf8'); - - c.on('connect', function() { - outstanding_reqs++; - c.write('GET / HTTP/1.0\r\n\r\n'); - }); - - c.on('data', function(chunk) { - //console.log(chunk); - res_buffer += chunk; - }); - - c.on('end', function() { - c.end(); - assert.ok(! /x-foo/.test(res_buffer), 'Trailer in HTTP/1.0 response.'); - outstanding_reqs--; - if (outstanding_reqs == 0) { - server.close(); - process.exit(); - } - }); -}); - -// now, we test an HTTP/1.1 request. -server.on('listening', function() { - var c = net.createConnection(common.PORT); - var res_buffer = ''; - var tid; - - c.setEncoding('utf8'); - - c.on('connect', function() { - outstanding_reqs++; - c.write('GET / HTTP/1.1\r\n\r\n'); - tid = setTimeout(assert.fail, 2000, 'Couldn\'t find last chunk.'); - }); - - c.on('data', function(chunk) { - //console.log(chunk); - res_buffer += chunk; - if (/0\r\n/.test(res_buffer)) { // got the end. - outstanding_reqs--; - clearTimeout(tid); - assert.ok( - /0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer), - 'No trailer in HTTP/1.1 response.' - ); - if (outstanding_reqs == 0) { - server.close(); - process.exit(); - } - } - }); -}); - -// now, see if the client sees the trailers. -server.on('listening', function() { - http.get({ port: common.PORT, path: '/hello', headers: {} }, function(res) { - res.on('end', function() { - //console.log(res.trailers); - assert.ok('x-foo' in res.trailers, 'Client doesn\'t see trailers.'); - outstanding_reqs--; - if (outstanding_reqs == 0) { - server.close(); - process.exit(); - } - }); - res.resume(); - }); - outstanding_reqs++; -}); diff --git a/test/simple/test-http-should-keep-alive.js b/test/simple/test-http-should-keep-alive.js deleted file mode 100644 index 943c34bb4..000000000 --- a/test/simple/test-http-should-keep-alive.js +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var SERVER_RESPONSES = [ - 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\n\r\n', - 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', - 'HTTP/1.0 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n', - 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\n\r\n', - 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n', - 'HTTP/1.1 200 ok\r\nContent-Length: 0\r\nConnection: close\r\n\r\n' -]; -var SHOULD_KEEP_ALIVE = [ - false, // HTTP/1.0, default - true, // HTTP/1.0, Connection: keep-alive - false, // HTTP/1.0, Connection: close - true, // HTTP/1.1, default - true, // HTTP/1.1, Connection: keep-alive - false // HTTP/1.1, Connection: close -]; -var requests = 0; -var responses = 0; -http.globalAgent.maxSockets = 5; - -var server = net.createServer(function(socket) { - socket.write(SERVER_RESPONSES[requests]); - ++requests; -}).listen(common.PORT, function() { - function makeRequest() { - var req = http.get({port: common.PORT}, function(res) { - assert.equal(req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], - SERVER_RESPONSES[responses] + ' should ' + - (SHOULD_KEEP_ALIVE[responses] ? '' : 'not ') + - 'Keep-Alive'); - ++responses; - if (responses < SHOULD_KEEP_ALIVE.length) { - makeRequest(); - } else { - server.close(); - } - res.resume(); - }); - } - - makeRequest(); -}); - -process.on('exit', function() { - assert.equal(requests, SERVER_RESPONSES.length); - assert.equal(responses, SHOULD_KEEP_ALIVE.length); -}); diff --git a/test/simple/test-http-status-code.js b/test/simple/test-http-status-code.js deleted file mode 100644 index ca56230d2..000000000 --- a/test/simple/test-http-status-code.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -// Simple test of Node's HTTP ServerResponse.statusCode -// ServerResponse.prototype.statusCode - -var testsComplete = 0; -var tests = [200, 202, 300, 404, 500]; -var testIdx = 0; - -var s = http.createServer(function(req, res) { - var t = tests[testIdx]; - res.writeHead(t, {'Content-Type': 'text/plain'}); - console.log('--\nserver: statusCode after writeHead: ' + res.statusCode); - assert.equal(res.statusCode, t); - res.end('hello world\n'); -}); - -s.listen(common.PORT, nextTest); - - -function nextTest() { - if (testIdx + 1 === tests.length) { - return s.close(); - } - var test = tests[testIdx]; - - http.get({ port: common.PORT }, function(response) { - console.log('client: expected status: ' + test); - console.log('client: statusCode: ' + response.statusCode); - assert.equal(response.statusCode, test); - response.on('end', function() { - testsComplete++; - testIdx += 1; - nextTest(); - }); - response.resume(); - }); -} - - -process.on('exit', function() { - assert.equal(4, testsComplete); -}); - diff --git a/test/simple/test-http-status-message.js b/test/simple/test-http-status-message.js deleted file mode 100644 index a8d7a3510..000000000 --- a/test/simple/test-http-status-message.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var s = http.createServer(function(req, res) { - res.statusCode = 200; - res.statusMessage = 'Custom Message'; - res.end(''); -}); - -s.listen(common.PORT, test); - - -function test() { - var bufs = []; - var client = net.connect(common.PORT, function() { - client.write('GET / HTTP/1.1\r\nConnection: close\r\n\r\n'); - }); - client.on('data', function(chunk) { - bufs.push(chunk); - }); - client.on('end', function() { - var head = Buffer.concat(bufs).toString('binary').split('\r\n')[0]; - assert.equal('HTTP/1.1 200 Custom Message', head); - console.log('ok'); - s.close(); - }); -} diff --git a/test/simple/test-http-timeout-overflow.js b/test/simple/test-http-timeout-overflow.js deleted file mode 100644 index 3e62612b3..000000000 --- a/test/simple/test-http-timeout-overflow.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var port = common.PORT; -var serverRequests = 0; -var clientRequests = 0; - -var server = http.createServer(function(req, res) { - serverRequests++; - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('OK'); -}); - -server.listen(port, function() { - function callback(){} - - var req = http.request({ - port: port, - path: '/', - agent: false - }, function(res) { - req.clearTimeout(callback); - - res.on('end', function() { - clientRequests++; - server.close(); - }) - - res.resume(); - }); - - // Overflow signed int32 - req.setTimeout(0xffffffff, callback); - req.end(); -}); - -process.once('exit', function() { - assert.equal(clientRequests, 1); - assert.equal(serverRequests, 1); -}); diff --git a/test/simple/test-http-timeout.js b/test/simple/test-http-timeout.js deleted file mode 100644 index ddd01c8a8..000000000 --- a/test/simple/test-http-timeout.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var port = common.PORT; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('OK'); -}); - -var agent = new http.Agent({maxSockets: 1}); - -server.listen(port, function() { - - for (var i = 0; i < 11; ++i) { - createRequest().end(); - } - - function callback(){} - - var count = 0; - - function createRequest() { - var req = http.request({port: port, path: '/', agent: agent}, function(res) { - - req.clearTimeout(callback); - - res.on('end', function() { - count++; - - if (count == 11) { - server.close(); - } - }) - - res.resume(); - }); - - req.setTimeout(1000, callback); - return req; - } -}); diff --git a/test/simple/test-http-unix-socket.js b/test/simple/test-http-unix-socket.js deleted file mode 100644 index 66d5403f6..000000000 --- a/test/simple/test-http-unix-socket.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var http = require('http'); - -var status_ok = false; // status code == 200? -var headers_ok = false; -var body_ok = false; - -var server = http.createServer(function(req, res) { - res.writeHead(200, { - 'Content-Type': 'text/plain', - 'Connection': 'close' - }); - res.write('hello '); - res.write('world\n'); - res.end(); -}); - -server.listen(common.PIPE, function() { - - var options = { - socketPath: common.PIPE, - path: '/' - }; - - var req = http.get(options, function(res) { - assert.equal(res.statusCode, 200); - status_ok = true; - - assert.equal(res.headers['content-type'], 'text/plain'); - headers_ok = true; - - res.body = ''; - res.setEncoding('utf8'); - - res.on('data', function(chunk) { - res.body += chunk; - }); - - res.on('end', function() { - assert.equal(res.body, 'hello world\n'); - body_ok = true; - server.close(function(error) { - assert.equal(error, undefined); - server.close(function(error) { - assert.equal(error && error.message, 'Not running'); - }); - }); - }); - }); - - req.on('error', function(e) { - console.log(e.stack); - process.exit(1); - }); - - req.end(); - -}); - -process.on('exit', function() { - assert.ok(status_ok); - assert.ok(headers_ok); - assert.ok(body_ok); -}); diff --git a/test/simple/test-http-upgrade-agent.js b/test/simple/test-http-upgrade-agent.js deleted file mode 100644 index 1077a983d..000000000 --- a/test/simple/test-http-upgrade-agent.js +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to -// the HTTP client. This test uses a raw TCP server to better control server -// behavior. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var net = require('net'); - -// Create a TCP server -var srv = net.createServer(function(c) { - var data = ''; - c.on('data', function(d) { - data += d.toString('utf8'); - - c.write('HTTP/1.1 101\r\n'); - c.write('hello: world\r\n'); - c.write('connection: upgrade\r\n'); - c.write('upgrade: websocket\r\n'); - c.write('\r\n'); - c.write('nurtzo'); - }); - - c.on('end', function() { - c.end(); - }); -}); - -var gotUpgrade = false; - -srv.listen(common.PORT, '127.0.0.1', function() { - - var options = { - port: common.PORT, - host: '127.0.0.1', - headers: { - 'upgrade': 'websocket' - } - }; - var name = options.host + ':' + options.port; - - var req = http.request(options); - req.end(); - - req.on('upgrade', function(res, socket, upgradeHead) { - // XXX: This test isn't fantastic, as it assumes that the entire response - // from the server will arrive in a single data callback - assert.equal(upgradeHead, 'nurtzo'); - - console.log(res.headers); - var expectedHeaders = { 'hello': 'world', - 'connection': 'upgrade', - 'upgrade': 'websocket' }; - assert.deepEqual(expectedHeaders, res.headers); - - // Make sure this request got removed from the pool. - assert(!http.globalAgent.sockets.hasOwnProperty(name)); - - req.on('close', function() { - socket.end(); - srv.close(); - - gotUpgrade = true; - }); - }); - -}); - -process.on('exit', function() { - assert.ok(gotUpgrade); -}); diff --git a/test/simple/test-http-upgrade-client.js b/test/simple/test-http-upgrade-client.js deleted file mode 100644 index 3bf5beccf..000000000 --- a/test/simple/test-http-upgrade-client.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to -// the HTTP client. This test uses a raw TCP server to better control server -// behavior. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); -var net = require('net'); - -// Create a TCP server -var srv = net.createServer(function(c) { - var data = ''; - c.on('data', function(d) { - data += d.toString('utf8'); - - c.write('HTTP/1.1 101\r\n'); - c.write('hello: world\r\n'); - c.write('connection: upgrade\r\n'); - c.write('upgrade: websocket\r\n'); - c.write('\r\n'); - c.write('nurtzo'); - }); - - c.on('end', function() { - c.end(); - }); -}); - -var gotUpgrade = false; - -srv.listen(common.PORT, '127.0.0.1', function() { - - var req = http.get({ port: common.PORT }); - req.on('upgrade', function(res, socket, upgradeHead) { - // XXX: This test isn't fantastic, as it assumes that the entire response - // from the server will arrive in a single data callback - assert.equal(upgradeHead, 'nurtzo'); - - console.log(res.headers); - var expectedHeaders = {'hello': 'world', - 'connection': 'upgrade', - 'upgrade': 'websocket' }; - assert.deepEqual(expectedHeaders, res.headers); - - socket.end(); - srv.close(); - - gotUpgrade = true; - }); -}); - -process.on('exit', function() { - assert.ok(gotUpgrade); -}); diff --git a/test/simple/test-http-upgrade-client2.js b/test/simple/test-http-upgrade-client2.js deleted file mode 100644 index fa39f2a57..000000000 --- a/test/simple/test-http-upgrade-client2.js +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var CRLF = '\r\n'; - -var server = http.createServer(); -server.on('upgrade', function(req, socket, head) { - socket.write('HTTP/1.1 101 Ok' + CRLF + - 'Connection: Upgrade' + CRLF + - 'Upgrade: Test' + CRLF + CRLF + 'head'); - socket.on('end', function() { - socket.end(); - }); -}); - -var successCount = 0; - -server.listen(common.PORT, function() { - - function upgradeRequest(fn) { - console.log('req'); - var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' }; - var request = http.request({ port: common.PORT, headers: header }); - var wasUpgrade = false; - - function onUpgrade(res, socket, head) { - console.log('client upgraded'); - wasUpgrade = true; - - request.removeListener('upgrade', onUpgrade); - socket.end(); - } - request.on('upgrade', onUpgrade); - - function onEnd() { - console.log('client end'); - request.removeListener('end', onEnd); - if (!wasUpgrade) { - throw new Error('hasn\'t received upgrade event'); - } else { - fn && process.nextTick(fn); - } - } - request.on('close', onEnd); - - request.write('head'); - - } - - upgradeRequest(function() { - successCount++; - upgradeRequest(function() { - successCount++; - // Test pass - console.log('Pass!'); - server.close(); - }); - }); - -}); - -process.on('exit', function() { - assert.equal(2, successCount); -}); diff --git a/test/simple/test-http-upgrade-server.js b/test/simple/test-http-upgrade-server.js deleted file mode 100644 index b514eff3c..000000000 --- a/test/simple/test-http-upgrade-server.js +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var util = require('util'); -var net = require('net'); -var http = require('http'); - - -var requests_recv = 0; -var requests_sent = 0; -var request_upgradeHead = null; - -function createTestServer() { - return new testServer(); -} - -function testServer() { - var server = this; - http.Server.call(server, function() {}); - - server.on('connection', function() { - requests_recv++; - }); - - server.on('request', function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('okay'); - res.end(); - }); - - server.on('upgrade', function(req, socket, upgradeHead) { - socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + - 'Upgrade: WebSocket\r\n' + - 'Connection: Upgrade\r\n' + - '\r\n\r\n'); - - request_upgradeHead = upgradeHead; - - socket.on('data', function(d) { - var data = d.toString('utf8'); - if (data == 'kill') { - socket.end(); - } else { - socket.write(data, 'utf8'); - } - }); - }); -} - -util.inherits(testServer, http.Server); - - -function writeReq(socket, data, encoding) { - requests_sent++; - socket.write(data); -} - - -/*----------------------------------------------- - connection: Upgrade with listener ------------------------------------------------*/ -function test_upgrade_with_listener(_server) { - var conn = net.createConnection(common.PORT); - conn.setEncoding('utf8'); - var state = 0; - - conn.on('connect', function() { - writeReq(conn, - 'GET / HTTP/1.1\r\n' + - 'Upgrade: WebSocket\r\n' + - 'Connection: Upgrade\r\n' + - '\r\n' + - 'WjN}|M(6'); - }); - - conn.on('data', function(data) { - state++; - - assert.equal('string', typeof data); - - if (state == 1) { - assert.equal('HTTP/1.1 101', data.substr(0, 12)); - assert.equal('WjN}|M(6', request_upgradeHead.toString('utf8')); - conn.write('test', 'utf8'); - } else if (state == 2) { - assert.equal('test', data); - conn.write('kill', 'utf8'); - } - }); - - conn.on('end', function() { - assert.equal(2, state); - conn.end(); - _server.removeAllListeners('upgrade'); - test_upgrade_no_listener(); - }); -} - -/*----------------------------------------------- - connection: Upgrade, no listener ------------------------------------------------*/ -var test_upgrade_no_listener_ended = false; - -function test_upgrade_no_listener() { - var conn = net.createConnection(common.PORT); - conn.setEncoding('utf8'); - - conn.on('connect', function() { - writeReq(conn, - 'GET / HTTP/1.1\r\n' + - 'Upgrade: WebSocket\r\n' + - 'Connection: Upgrade\r\n' + - '\r\n'); - }); - - conn.on('end', function() { - test_upgrade_no_listener_ended = true; - conn.end(); - }); - - conn.on('close', function() { - test_standard_http(); - }); -} - -/*----------------------------------------------- - connection: normal ------------------------------------------------*/ -function test_standard_http() { - var conn = net.createConnection(common.PORT); - conn.setEncoding('utf8'); - - conn.on('connect', function() { - writeReq(conn, 'GET / HTTP/1.1\r\n\r\n'); - }); - - conn.once('data', function(data) { - assert.equal('string', typeof data); - assert.equal('HTTP/1.1 200', data.substr(0, 12)); - conn.end(); - }); - - conn.on('close', function() { - server.close(); - }); -} - - -var server = createTestServer(); - -server.listen(common.PORT, function() { - // All tests get chained after this: - test_upgrade_with_listener(server); -}); - - -/*----------------------------------------------- - Fin. ------------------------------------------------*/ -process.on('exit', function() { - assert.equal(3, requests_recv); - assert.equal(3, requests_sent); - assert.ok(test_upgrade_no_listener_ended); -}); diff --git a/test/simple/test-http-upgrade-server2.js b/test/simple/test-http-upgrade-server2.js deleted file mode 100644 index e617d3b1c..000000000 --- a/test/simple/test-http-upgrade-server2.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var server = http.createServer(function(req, res) { - common.error('got req'); - throw new Error('This shouldn\'t happen.'); -}); - -server.on('upgrade', function(req, socket, upgradeHead) { - common.error('got upgrade event'); - // test that throwing an error from upgrade gets - // is uncaught - throw new Error('upgrade error'); -}); - -var gotError = false; - -process.on('uncaughtException', function(e) { - common.error('got \'clientError\' event'); - assert.equal('upgrade error', e.message); - gotError = true; - process.exit(0); -}); - - -server.listen(common.PORT, function() { - var c = net.createConnection(common.PORT); - - c.on('connect', function() { - common.error('client wrote message'); - c.write('GET /blah HTTP/1.1\r\n' + - 'Upgrade: WebSocket\r\n' + - 'Connection: Upgrade\r\n' + - '\r\n\r\nhello world'); - }); - - c.on('end', function() { - c.end(); - }); - - c.on('close', function() { - common.error('client close'); - server.close(); - }); -}); - -process.on('exit', function() { - assert.ok(gotError); -}); diff --git a/test/simple/test-http-url.parse-auth-with-header-in-request.js b/test/simple/test-http-url.parse-auth-with-header-in-request.js deleted file mode 100644 index 5ac789068..000000000 --- a/test/simple/test-http-url.parse-auth-with-header-in-request.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -var testURL = url.parse('http://asdf:qwer@localhost:' + common.PORT); -// the test here is if you set a specific authorization header in the -// request we should not override that with basic auth -testURL.headers = { - Authorization: 'NoAuthForYOU' -}; - -function check(request) { - // the correct authorization header is be passed - assert.strictEqual(request.headers.authorization, 'NoAuthForYOU'); -} - -var server = http.createServer(function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - http.request(testURL).end(); -}); diff --git a/test/simple/test-http-url.parse-auth.js b/test/simple/test-http-url.parse-auth.js deleted file mode 100644 index 4c07d5ffc..000000000 --- a/test/simple/test-http-url.parse-auth.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -// username = "user", password = "pass:" -var testURL = url.parse('http://user:pass%3A@localhost:' + common.PORT); - -function check(request) { - // the correct authorization header is be passed - assert.strictEqual(request.headers.authorization, 'Basic dXNlcjpwYXNzOg=='); -} - -var server = http.createServer(function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - http.request(testURL).end(); -}); diff --git a/test/simple/test-http-url.parse-basic.js b/test/simple/test-http-url.parse-basic.js deleted file mode 100644 index 8bf12b1c2..000000000 --- a/test/simple/test-http-url.parse-basic.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -var testURL = url.parse('http://localhost:' + common.PORT); - -// make sure the basics work -function check(request) { - // default method should still be get - assert.strictEqual(request.method, 'GET'); - // there are no URL params, so you should not see any - assert.strictEqual(request.url, '/'); - // the host header should use the url.parse.hostname - assert.strictEqual(request.headers.host, - testURL.hostname + ':' + testURL.port); -} - -var server = http.createServer(function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - var clientRequest = http.request(testURL); - // since there is a little magic with the agent - // make sure that an http request uses the http.Agent - assert.ok(clientRequest.agent instanceof http.Agent); - clientRequest.end(); -}); diff --git a/test/simple/test-http-url.parse-https.request.js b/test/simple/test-http-url.parse-https.request.js deleted file mode 100644 index b83f0df9f..000000000 --- a/test/simple/test-http-url.parse-https.request.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var url = require('url'); -var fs = require('fs'); -var clientRequest; - -// https options -var httpsOptions = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var testURL = url.parse('https://localhost:' + common.PORT); -testURL.rejectUnauthorized = false; - -function check(request) { - // assert that I'm https - assert.ok(request.socket._secureEstablished); -} - -var server = https.createServer(httpsOptions, function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - var clientRequest = https.request(testURL); - // since there is a little magic with the agent - // make sure that the request uses the https.Agent - assert.ok(clientRequest.agent instanceof https.Agent); - clientRequest.end(); -}); diff --git a/test/simple/test-http-url.parse-only-support-http-https-protocol.js b/test/simple/test-http-url.parse-only-support-http-https-protocol.js deleted file mode 100644 index 0f5712641..000000000 --- a/test/simple/test-http-url.parse-only-support-http-https-protocol.js +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - - -assert.throws(function() { - http.request(url.parse('file:///whatever')); -}, function(err) { - if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "file:" not supported. Expected "http:".'); - return true; - } -}); - -assert.throws(function() { - http.request(url.parse('mailto:asdf@asdf.com')); -}, function(err) { - if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "mailto:" not supported. Expected "http:".'); - return true; - } -}); - -assert.throws(function() { - http.request(url.parse('ftp://www.example.com')); -}, function(err) { - if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "ftp:" not supported. Expected "http:".'); - return true; - } -}); - -assert.throws(function() { - http.request(url.parse('javascript:alert(\'hello\');')); -}, function(err) { - if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "javascript:" not supported. Expected "http:".'); - return true; - } -}); - -assert.throws(function() { - http.request(url.parse('xmpp:isaacschlueter@jabber.org')); -}, function(err) { - if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "xmpp:" not supported. Expected "http:".'); - return true; - } -}); - -assert.throws(function() { - http.request(url.parse('f://some.host/path')); -}, function(err) { - if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "f:" not supported. Expected "http:".'); - return true; - } -}); - -//TODO do I need to test url.parse(notPrococol.example.com)? diff --git a/test/simple/test-http-url.parse-path.js b/test/simple/test-http-url.parse-path.js deleted file mode 100644 index 8ef09520c..000000000 --- a/test/simple/test-http-url.parse-path.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -var testURL = url.parse('http://localhost:' + common.PORT + '/asdf'); - -function check(request) { - // a path should come over - assert.strictEqual(request.url, '/asdf'); -} - -var server = http.createServer(function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - http.request(testURL).end(); -}); diff --git a/test/simple/test-http-url.parse-post.js b/test/simple/test-http-url.parse-post.js deleted file mode 100644 index be93166d5..000000000 --- a/test/simple/test-http-url.parse-post.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var https = require('https'); -var url = require('url'); - -var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); -testURL.method = 'POST'; - -function check(request) { - //url.parse should not mess with the method - assert.strictEqual(request.method, 'POST'); - //everything else should be right - assert.strictEqual(request.url, '/asdf?qwer=zxcv'); - //the host header should use the url.parse.hostname - assert.strictEqual(request.headers.host, - testURL.hostname + ':' + testURL.port); -} - -var server = http.createServer(function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - http.request(testURL).end(); -}); diff --git a/test/simple/test-http-url.parse-search.js b/test/simple/test-http-url.parse-search.js deleted file mode 100644 index 3b6727d0b..000000000 --- a/test/simple/test-http-url.parse-search.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var https = require('https'); -var url = require('url'); - -var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); - -function check(request) { - // a path should come over with params - assert.strictEqual(request.url, '/asdf?qwer=zxcv'); -} - -var server = http.createServer(function(request, response) { - // run the check function - check.call(this, request, response); - response.writeHead(200, {}); - response.end('ok'); - server.close(); -}); - -server.listen(common.PORT, function() { - // make the request - http.request(testURL).end(); -}); diff --git a/test/simple/test-http-wget.js b/test/simple/test-http-wget.js deleted file mode 100644 index b6cf7d8be..000000000 --- a/test/simple/test-http-wget.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var http = require('http'); - -// wget sends an HTTP/1.0 request with Connection: Keep-Alive -// -// Sending back a chunked response to an HTTP/1.0 client would be wrong, -// so what has to happen in this case is that the connection is closed -// by the server after the entity body if the Content-Length was not -// sent. -// -// If the Content-Length was sent, we can probably safely honor the -// keep-alive request, even though HTTP 1.0 doesn't say that the -// connection can be kept open. Presumably any client sending this -// header knows that it is extending HTTP/1.0 and can handle the -// response. We don't test that here however, just that if the -// content-length is not provided, that the connection is in fact -// closed. - -var server_response = ''; -var client_got_eof = false; -var connection_was_closed = false; - -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello '); - res.write('world\n'); - res.end(); -}); -server.listen(common.PORT); - -server.on('listening', function() { - var c = net.createConnection(common.PORT); - - c.setEncoding('utf8'); - - c.on('connect', function() { - c.write('GET / HTTP/1.0\r\n' + - 'Connection: Keep-Alive\r\n\r\n'); - }); - - c.on('data', function(chunk) { - console.log(chunk); - server_response += chunk; - }); - - c.on('end', function() { - client_got_eof = true; - console.log('got end'); - c.end(); - }); - - c.on('close', function() { - connection_was_closed = true; - console.log('got close'); - server.close(); - }); -}); - -process.on('exit', function() { - var m = server_response.split('\r\n\r\n'); - assert.equal(m[1], 'hello world\n'); - assert.ok(client_got_eof); - assert.ok(connection_was_closed); -}); diff --git a/test/simple/test-http-write-callbacks.js b/test/simple/test-http-write-callbacks.js deleted file mode 100644 index 3a740ae5b..000000000 --- a/test/simple/test-http-write-callbacks.js +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var serverEndCb = false; -var serverIncoming = ''; -var serverIncomingExpect = 'bazquuxblerg'; - -var clientEndCb = false; -var clientIncoming = ''; -var clientIncomingExpect = 'asdffoobar'; - -process.on('exit', function() { - assert(serverEndCb); - assert.equal(serverIncoming, serverIncomingExpect); - assert(clientEndCb); - assert.equal(clientIncoming, clientIncomingExpect); - console.log('ok'); -}); - -// Verify that we get a callback when we do res.write(..., cb) -var server = http.createServer(function(req, res) { - res.statusCode = 400; - res.end('Bad Request.\nMust send Expect:100-continue\n'); -}); - -server.on('checkContinue', function(req, res) { - server.close(); - assert.equal(req.method, 'PUT'); - res.writeContinue(function() { - // continue has been written - req.on('end', function() { - res.write('asdf', function(er) { - assert.ifError(er); - res.write('foo', 'ascii', function(er) { - assert.ifError(er); - res.end(new Buffer('bar'), 'buffer', function(er) { - serverEndCb = true; - }); - }); - }); - }); - }); - - req.setEncoding('ascii'); - req.on('data', function(c) { - serverIncoming += c; - }); -}); - -server.listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - method: 'PUT', - headers: { 'expect': '100-continue' } - }); - req.on('continue', function() { - // ok, good to go. - req.write('YmF6', 'base64', function(er) { - assert.ifError(er); - req.write(new Buffer('quux'), function(er) { - assert.ifError(er); - req.end('626c657267', 'hex', function(er) { - assert.ifError(er); - clientEndCb = true; - }); - }); - }); - }); - req.on('response', function(res) { - // this should not come until after the end is flushed out - assert(clientEndCb); - res.setEncoding('ascii'); - res.on('data', function(c) { - clientIncoming += c; - }); - }); -}); diff --git a/test/simple/test-http-write-empty-string.js b/test/simple/test-http-write-empty-string.js deleted file mode 100644 index baf9c27f4..000000000 --- a/test/simple/test-http-write-empty-string.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var server = http.createServer(function(request, response) { - console.log('responding to ' + request.url); - - response.writeHead(200, {'Content-Type': 'text/plain'}); - response.write('1\n'); - response.write(''); - response.write('2\n'); - response.write(''); - response.end('3\n'); - - this.close(); -}); - -var response = ''; - -process.on('exit', function() { - assert.equal('1\n2\n3\n', response); -}); - - -server.listen(common.PORT, function() { - http.get({ port: common.PORT }, function(res) { - assert.equal(200, res.statusCode); - res.setEncoding('ascii'); - res.on('data', function(chunk) { - response += chunk; - }); - common.error('Got /hello response'); - }); -}); - diff --git a/test/simple/test-http-write-head.js b/test/simple/test-http-write-head.js deleted file mode 100644 index 88923ef27..000000000 --- a/test/simple/test-http-write-head.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -// Verify that ServerResponse.writeHead() works as setHeader. -// Issue 5036 on github. - -var s = http.createServer(function(req, res) { - res.setHeader('test', '1'); - - // toLowerCase() is used on the name argument, so it must be a string. - var threw = false; - try { - res.setHeader(0xf00, 'bar'); - } catch (e) { - assert.ok(e instanceof TypeError); - threw = true; - } - assert.ok(threw, 'Non-string names should throw'); - - res.writeHead(200, { Test: '2' }); - res.end(); -}); - -s.listen(common.PORT, runTest); - -function runTest() { - http.get({ port: common.PORT }, function(response) { - response.on('end', function() { - assert.equal(response.headers['test'], '2'); - assert(response.rawHeaders.indexOf('Test') !== -1); - s.close(); - }); - response.resume(); - }); -} diff --git a/test/simple/test-http-zero-length-write.js b/test/simple/test-http-zero-length-write.js deleted file mode 100644 index e68f947c3..000000000 --- a/test/simple/test-http-zero-length-write.js +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var http = require('http'); - -var Stream = require('stream'); - -function getSrc() { - // An old-style readable stream. - // The Readable class prevents this behavior. - var src = new Stream(); - - // start out paused, just so we don't miss anything yet. - var paused = false; - src.pause = function() { - paused = true; - }; - src.resume = function() { - paused = false; - }; - - var chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; - var interval = setInterval(function() { - if (paused) - return - - var chunk = chunks.shift(); - if (chunk !== undefined) { - src.emit('data', chunk); - } else { - src.emit('end'); - clearInterval(interval); - } - }, 1); - - return src; -} - - -var expect = 'asdffoobar'; - -var server = http.createServer(function(req, res) { - var actual = ''; - req.setEncoding('utf8'); - req.on('data', function(c) { - actual += c; - }); - req.on('end', function() { - assert.equal(actual, expect); - getSrc().pipe(res); - }); - server.close(); -}); - -server.listen(common.PORT, function() { - var req = http.request({ port: common.PORT, method: 'POST' }); - var actual = ''; - req.on('response', function(res) { - res.setEncoding('utf8'); - res.on('data', function(c) { - actual += c; - }); - res.on('end', function() { - assert.equal(actual, expect); - }); - }); - getSrc().pipe(req); -}); - -process.on('exit', function(c) { - if (!c) console.log('ok'); -}); diff --git a/test/simple/test-http.js b/test/simple/test-http.js deleted file mode 100644 index fa388356d..000000000 --- a/test/simple/test-http.js +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var url = require('url'); - -function p(x) { - common.error(common.inspect(x)); -} - -var responses_sent = 0; -var responses_recvd = 0; -var body0 = ''; -var body1 = ''; - -var server = http.Server(function(req, res) { - if (responses_sent == 0) { - assert.equal('GET', req.method); - assert.equal('/hello', url.parse(req.url).pathname); - - console.dir(req.headers); - assert.equal(true, 'accept' in req.headers); - assert.equal('*/*', req.headers['accept']); - - assert.equal(true, 'foo' in req.headers); - assert.equal('bar', req.headers['foo']); - } - - if (responses_sent == 1) { - assert.equal('POST', req.method); - assert.equal('/world', url.parse(req.url).pathname); - this.close(); - } - - req.on('end', function() { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('The path was ' + url.parse(req.url).pathname); - res.end(); - responses_sent += 1; - }); - req.resume(); - - //assert.equal('127.0.0.1', res.connection.remoteAddress); -}); -server.listen(common.PORT); - -server.on('listening', function() { - var agent = new http.Agent({ port: common.PORT, maxSockets: 1 }); - http.get({ - port: common.PORT, - path: '/hello', - headers: {'Accept': '*/*', 'Foo': 'bar'}, - agent: agent - }, function(res) { - assert.equal(200, res.statusCode); - responses_recvd += 1; - res.setEncoding('utf8'); - res.on('data', function(chunk) { body0 += chunk; }); - common.debug('Got /hello response'); - }); - - setTimeout(function() { - var req = http.request({ - port: common.PORT, - method: 'POST', - path: '/world', - agent: agent - }, function(res) { - assert.equal(200, res.statusCode); - responses_recvd += 1; - res.setEncoding('utf8'); - res.on('data', function(chunk) { body1 += chunk; }); - common.debug('Got /world response'); - }); - req.end(); - }, 1); -}); - -process.on('exit', function() { - common.debug('responses_recvd: ' + responses_recvd); - assert.equal(2, responses_recvd); - - common.debug('responses_sent: ' + responses_sent); - assert.equal(2, responses_sent); - - assert.equal('The path was /hello', body0); - assert.equal('The path was /world', body1); -}); - diff --git a/test/simple/test-https-agent.js b/test/simple/test-https-agent.js deleted file mode 100644 index 34fa15c73..000000000 --- a/test/simple/test-https-agent.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - - -var server = https.Server(options, function(req, res) { - res.writeHead(200); - res.end('hello world\n'); -}); - - -var responses = 0; -var N = 10; -var M = 10; - -server.listen(common.PORT, function() { - for (var i = 0; i < N; i++) { - setTimeout(function() { - for (var j = 0; j < M; j++) { - https.get({ - path: '/', - port: common.PORT, - rejectUnauthorized: false - }, function(res) { - res.resume(); - console.log(res.statusCode); - if (++responses == N * M) server.close(); - }).on('error', function(e) { - console.log(e.message); - process.exit(1); - }); - } - }, i); - } -}); - - -process.on('exit', function() { - assert.equal(N * M, responses); -}); diff --git a/test/simple/test-https-byteswritten.js b/test/simple/test-https-byteswritten.js deleted file mode 100644 index 21c300efa..000000000 --- a/test/simple/test-https-byteswritten.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var http = require('http'); -var https = require('https'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var body = 'hello world\n'; - -var httpsServer = https.createServer(options, function(req, res) { - res.on('finish', function() { - assert(typeof(req.connection.bytesWritten) === 'number'); - assert(req.connection.bytesWritten > 0); - httpsServer.close(); - console.log('ok'); - }); - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end(body); -}); - -httpsServer.listen(common.PORT, function() { - https.get({ - port: common.PORT, - rejectUnauthorized: false - }); -}); diff --git a/test/simple/test-https-client-checkServerIdentity.js b/test/simple/test-https-client-checkServerIdentity.js deleted file mode 100644 index a985d23e5..000000000 --- a/test/simple/test-https-client-checkServerIdentity.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); -var path = require('path'); - -var options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-cert.pem')) -}; - -var reqCount = 0; - -var server = https.createServer(options, function (req, res) { - ++reqCount; - res.writeHead(200); - res.end(); - req.resume(); -}).listen(common.PORT, function () { - authorized(); -}); - -function authorized() { - var req = https.request({ - port: common.PORT, - rejectUnauthorized: true, - ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] - }, function (res) { - assert(false); - }); - req.on('error', function (err) { - override(); - }); - req.end(); -} - -function override() { - var options = { - port: common.PORT, - rejectUnauthorized: true, - ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))], - checkServerIdentity: function (host, cert) { - return false; - } - }; - options.agent = new https.Agent(options); - var req = https.request(options, function (res) { - assert(req.socket.authorized); - server.close(); - }); - req.on('error', function (err) { - throw err; - }); - req.end(); -} - -process.on('exit', function () { - assert.equal(reqCount, 1); -}); diff --git a/test/simple/test-https-client-get-url.js b/test/simple/test-https-client-get-url.js deleted file mode 100644 index ae5613c14..000000000 --- a/test/simple/test-https-client-get-url.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -// disable strict server certificate validation by the client -process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); - -var seen_req = false; - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = https.createServer(options, function(req, res) { - assert.equal('GET', req.method); - assert.equal('/foo?bar', req.url); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello\n'); - res.end(); - server.close(); - seen_req = true; -}); - -server.listen(common.PORT, function() { - https.get('https://127.0.0.1:' + common.PORT + '/foo?bar'); -}); - -process.on('exit', function() { - assert(seen_req); -}); diff --git a/test/simple/test-https-client-reject.js b/test/simple/test-https-client-reject.js deleted file mode 100644 index bf191da1d..000000000 --- a/test/simple/test-https-client-reject.js +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); -var path = require('path'); - -var options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) -}; - -var reqCount = 0; - -var server = https.createServer(options, function(req, res) { - ++reqCount; - res.writeHead(200); - res.end(); - req.resume(); -}).listen(common.PORT, function() { - unauthorized(); -}); - -function unauthorized() { - var req = https.request({ - port: common.PORT, - rejectUnauthorized: false - }, function(res) { - assert(!req.socket.authorized); - res.resume(); - rejectUnauthorized(); - }); - req.on('error', function(err) { - throw err; - }); - req.end(); -} - -function rejectUnauthorized() { - var options = { - port: common.PORT - }; - options.agent = new https.Agent(options); - var req = https.request(options, function(res) { - assert(false); - }); - req.on('error', function(err) { - authorized(); - }); - req.end(); -} - -function authorized() { - var options = { - port: common.PORT, - ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))] - }; - options.agent = new https.Agent(options); - var req = https.request(options, function(res) { - res.resume(); - assert(req.socket.authorized); - server.close(); - }); - req.on('error', function(err) { - assert(false); - }); - req.end(); -} - -process.on('exit', function() { - assert.equal(reqCount, 2); -}); diff --git a/test/simple/test-https-client-resume.js b/test/simple/test-https-client-resume.js deleted file mode 100644 index 0433afdd9..000000000 --- a/test/simple/test-https-client-resume.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Create an ssl server. First connection, validate that not resume. -// Cache session and close connection. Use session on second connection. -// ASSERT resumption. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') -}; - -var connections = 0; - -// create server -var server = https.createServer(options, function(res, res) { - res.end('Goodbye'); - connections++; -}); - -// start listening -server.listen(common.PORT, function() { - - var session1 = null; - var client1 = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - console.log('connect1'); - assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); - session1 = client1.getSession(); - client1.write('GET / HTTP/1.0\r\n' + - 'Server: 127.0.0.1\r\n' + - '\r\n'); - }); - - client1.on('close', function() { - console.log('close1'); - - var opts = { - port: common.PORT, - rejectUnauthorized: false, - session: session1 - }; - - var client2 = tls.connect(opts, function() { - console.log('connect2'); - assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); - client2.write('GET / HTTP/1.0\r\n' + - 'Server: 127.0.0.1\r\n' + - '\r\n'); - }); - - client2.on('close', function() { - console.log('close2'); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(2, connections); -}); diff --git a/test/simple/test-https-connecting-to-http.js b/test/simple/test-https-connecting-to-http.js deleted file mode 100644 index 50bb2a8a3..000000000 --- a/test/simple/test-https-connecting-to-http.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -// This tests the situation where you try to connect a https client -// to an http server. You should get an error and exit. -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var http = require('http'); - - -var reqCount = 0; -var resCount = 0; -var reqErrorCount = 0; -var body = 'hello world\n'; - - -var server = http.createServer(function(req, res) { - reqCount++; - console.log('got request'); - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end(body); -}); - - -server.listen(common.PORT, function() { - var req = https.get({ port: common.PORT }, function(res) { - resCount++; - }); - - req.on('error', function(e) { - console.log('Got expected error: ', e.message); - server.close(); - reqErrorCount++; - }); -}); - - -process.on('exit', function() { - assert.equal(0, reqCount); - assert.equal(0, resCount); - assert.equal(1, reqErrorCount); -}); diff --git a/test/simple/test-https-drain.js b/test/simple/test-https-drain.js deleted file mode 100644 index 5509a2474..000000000 --- a/test/simple/test-https-drain.js +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); -var path = require('path'); - -var options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) -}; - -var bufSize = 1024 * 1024; -var sent = 0; -var received = 0; - -var server = https.createServer(options, function(req, res) { - res.writeHead(200); - req.pipe(res); -}); - -server.listen(common.PORT, function() { - var resumed = false; - var req = https.request({ - method: 'POST', - port: common.PORT, - rejectUnauthorized: false - }, function(res) { - var timer; - res.pause(); - common.debug('paused'); - send(); - function send() { - if (req.write(new Buffer(bufSize))) { - sent += bufSize; - assert.ok(sent < 100 * 1024 * 1024); // max 100MB - return process.nextTick(send); - } - sent += bufSize; - common.debug('sent: ' + sent); - resumed = true; - res.resume(); - common.debug('resumed'); - timer = setTimeout(function() { - process.exit(1); - }, 1000); - } - - res.on('data', function(data) { - assert.ok(resumed); - if (timer) { - clearTimeout(timer); - timer = null; - } - received += data.length; - if (received >= sent) { - common.debug('received: ' + received); - req.end(); - server.close(); - } - }); - }); - req.write('a'); - ++sent; -}); - -process.on('exit', function() { - assert.equal(sent, received); -}); diff --git a/test/simple/test-https-eof-for-eom.js b/test/simple/test-https-eof-for-eom.js deleted file mode 100644 index 7a465b865..000000000 --- a/test/simple/test-https-eof-for-eom.js +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// I hate HTTP. One way of terminating an HTTP response is to not send -// a content-length header, not send a transfer-encoding: chunked header, -// and simply terminate the TCP connection. That is identity -// transfer-encoding. -// -// This test is to be sure that the https client is handling this case -// correctly. -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var https = require('https'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - - -var server = tls.Server(options, function(socket) { - console.log('2) Server got request'); - socket.write('HTTP/1.1 200 OK\r\n' + - 'Date: Tue, 15 Feb 2011 22:14:54 GMT\r\n' + - 'Expires: -1\r\n' + - 'Cache-Control: private, max-age=0\r\n' + - 'Set-Cookie: xyz\r\n' + - 'Set-Cookie: abc\r\n' + - 'Server: gws\r\n' + - 'X-XSS-Protection: 1; mode=block\r\n' + - 'Connection: close\r\n' + - '\r\n'); - - socket.write('hello world\n'); - - setTimeout(function() { - socket.end('hello world\n'); - console.log('4) Server finished response'); - }, 100); -}); - - -var gotHeaders = false; -var gotEnd = false; -var bodyBuffer = ''; - -server.listen(common.PORT, function() { - console.log('1) Making Request'); - var req = https.get({ - port: common.PORT, - rejectUnauthorized: false - }, function(res) { - server.close(); - console.log('3) Client got response headers.'); - - assert.equal('gws', res.headers.server); - gotHeaders = true; - - res.setEncoding('utf8'); - res.on('data', function(s) { - bodyBuffer += s; - }); - - res.on('end', function() { - console.log('5) Client got "end" event.'); - gotEnd = true; - }); - }); -}); - -process.on('exit', function() { - assert.ok(gotHeaders); - assert.ok(gotEnd); - assert.equal('hello world\nhello world\n', bodyBuffer); -}); - diff --git a/test/simple/test-https-foafssl.js b/test/simple/test-https-foafssl.js deleted file mode 100644 index c9fc746e8..000000000 --- a/test/simple/test-https-foafssl.js +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var join = require('path').join; - -var fs = require('fs'); -var spawn = require('child_process').spawn; - -var https = require('https'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/agent.key'), - cert: fs.readFileSync(common.fixturesDir + '/agent.crt'), - requestCert: true -}; - -var reqCount = 0; -var CRLF = '\r\n'; -var body = 'hello world\n'; -var cert; -var subjectaltname; -var modulus; -var exponent; - -var server = https.createServer(options, function(req, res) { - reqCount++; - console.log('got request'); - - cert = req.connection.getPeerCertificate(); - - subjectaltname = cert.subjectaltname; - modulus = cert.modulus; - exponent = cert.exponent; - - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end(body); -}); - -server.listen(common.PORT, function() { - var args = ['s_client', - '-quiet', - '-connect', '127.0.0.1:' + common.PORT, - '-cert', join(common.fixturesDir, 'foafssl.crt'), - '-key', join(common.fixturesDir, 'foafssl.key')]; - - var client = spawn(common.opensslCli, args); - - client.stdout.on('data', function(data) { - var message = data.toString(); - var contents = message.split(CRLF + CRLF).pop(); - assert.equal(body, contents); - server.close(); - }); - - client.stdin.write('GET /\n\n'); - - client.on('error', function(error) { - throw error; - }); -}); - -process.on('exit', function() { - assert.equal(subjectaltname, 'URI:http://example.com/#me'); - assert.equal(modulus, 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09' + - 'BBC3A5519F349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C2896' + - '4694B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560CDE9C13' + - '455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06AFF8BE191B7920' + - 'DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF82100B03A4F0FF1809278E4DD' + - 'FDA7DE954ED56DC7AD9A47EEBC37D771A366FC60A5BCB72373BEC180649B3EFA0E90' + - '92707210B41B90032BB18BC91F2046EBDAF1191F4A4E26D71879C4C7867B62FCD508' + - 'E8CE66E82D128A71E915809FCF44E8DE774067F1DE5D70B9C03687'); - assert.equal(exponent, '10001'); -}); diff --git a/test/simple/test-https-localaddress-bind-error.js b/test/simple/test-https-localaddress-bind-error.js deleted file mode 100644 index 0c4f8da4c..000000000 --- a/test/simple/test-https-localaddress-bind-error.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var invalidLocalAddress = '1.2.3.4'; -var gotError = false; - -var server = https.createServer(options, function(req, res) { - console.log("Connect from: " + req.connection.remoteAddress); - - req.on('end', function() { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('You are from: ' + req.connection.remoteAddress); - }); - req.resume(); -}); - -server.listen(common.PORT, "127.0.0.1", function() { - var req = https.request({ - host: 'localhost', - port: common.PORT, - path: '/', - method: 'GET', - localAddress: invalidLocalAddress - }, function(res) { - assert.fail('unexpectedly got response from server'); - }).on('error', function(e) { - console.log('client got error: ' + e.message); - gotError = true; - server.close(); - }).end(); -}); - -process.on('exit', function() { - assert.ok(gotError); -}); diff --git a/test/simple/test-https-localaddress.js b/test/simple/test-https-localaddress.js deleted file mode 100644 index f703d41ae..000000000 --- a/test/simple/test-https-localaddress.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var https = require('https'), - fs = require('fs'), - assert = require('assert'); - -if (['linux', 'win32'].indexOf(process.platform) == -1) { - console.log('Skipping platform-specific test.'); - process.exit(); -} - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = https.createServer(options, function (req, res) { - console.log("Connect from: " + req.connection.remoteAddress); - assert.equal('127.0.0.2', req.connection.remoteAddress); - - req.on('end', function() { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('You are from: ' + req.connection.remoteAddress); - }); - req.resume(); -}); - -server.listen(common.PORT, "127.0.0.1", function() { - var options = { - host: 'localhost', - port: common.PORT, - path: '/', - method: 'GET', - localAddress: '127.0.0.2', - rejectUnauthorized: false - }; - - var req = https.request(options, function(res) { - res.on('end', function() { - server.close(); - process.exit(); - }); - res.resume(); - }); - req.end(); -}); diff --git a/test/simple/test-https-pfx.js b/test/simple/test-https-pfx.js deleted file mode 100644 index 9da1ff8ee..000000000 --- a/test/simple/test-https-pfx.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var fs = require('fs'); - -var pfx = fs.readFileSync(common.fixturesDir + '/test_cert.pfx'); - -var options = { - host: '127.0.0.1', - port: common.PORT, - path: '/', - pfx: pfx, - passphrase: 'sample', - requestCert: true, - rejectUnauthorized: false -}; - -var server = https.createServer(options, function(req, res) { - assert.equal(req.socket.authorized, false); // not a client cert - assert.equal(req.socket.authorizationError, 'DEPTH_ZERO_SELF_SIGNED_CERT'); - res.writeHead(200); - res.end('OK'); -}); - -server.listen(options.port, options.host, function() { - var data = ''; - - https.get(options, function(res) { - res.on('data', function(data_) { data += data_ }); - res.on('end', function() { server.close() }); - }); - - process.on('exit', function() { - assert.equal(data, 'OK'); - }); -}); diff --git a/test/simple/test-https-req-split.js b/test/simple/test-https-req-split.js deleted file mode 100644 index db54d7237..000000000 --- a/test/simple/test-https-req-split.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -// disable strict server certificate validation by the client -process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var tls = require('tls'); -var fs = require('fs'); - -var seen_req = false; - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -// Force splitting incoming data -tls.SLAB_BUFFER_SIZE = 1; - -var server = https.createServer(options); -server.on('upgrade', function(req, socket, upgrade) { - socket.on('data', function(data) { - throw new Error('Unexpected data: ' + data); - }); - socket.end('HTTP/1.1 200 Ok\r\n\r\n'); - seen_req = true; -}); - -server.listen(common.PORT, function() { - var req = https.request({ - host: '127.0.0.1', - port: common.PORT, - agent: false, - headers: { - Connection: 'Upgrade', - Upgrade: 'Websocket' - } - }, function() { - req.socket.destroy(); - server.close(); - }); - - req.end(); -}); - -process.on('exit', function() { - assert(seen_req); - console.log('ok'); -}); diff --git a/test/simple/test-https-set-timeout-server.js b/test/simple/test-https-set-timeout-server.js deleted file mode 100644 index e4dc1e360..000000000 --- a/test/simple/test-https-set-timeout-server.js +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var https = require('https'); -var tls = require('tls'); -var fs = require('fs'); - -var tests = []; - -var serverOptions = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -function test(fn) { - if (!tests.length) - process.nextTick(run); - tests.push(fn); -} - -function run() { - var fn = tests.shift(); - if (fn) { - console.log('# %s', fn.name); - fn(run); - } else - console.log('ok'); -} - -test(function serverTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = https.createServer(serverOptions, function(req, res) { - // just do nothing, we should get a timeout event. - }); - server.listen(common.PORT); - server.setTimeout(50, function(socket) { - caughtTimeout = true; - socket.destroy(); - server.close(); - cb(); - }); - https.get({ - port: common.PORT, - rejectUnauthorized: false - }).on('error', function() {}); -}); - -test(function serverRequestTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = https.createServer(serverOptions, function(req, res) { - // just do nothing, we should get a timeout event. - req.setTimeout(50, function() { - caughtTimeout = true; - req.socket.destroy(); - server.close(); - cb(); - }); - }); - server.listen(common.PORT); - var req = https.request({ - port: common.PORT, - method: 'POST', - rejectUnauthorized: false - }); - req.on('error', function() {}); - req.write('Hello'); - // req is in progress -}); - -test(function serverResponseTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = https.createServer(serverOptions, function(req, res) { - // just do nothing, we should get a timeout event. - res.setTimeout(50, function() { - caughtTimeout = true; - res.socket.destroy(); - server.close(); - cb(); - }); - }); - server.listen(common.PORT); - https.get({ - port: common.PORT, - rejectUnauthorized: false - }).on('error', function() {}); -}); - -test(function serverRequestNotTimeoutAfterEnd(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(caughtTimeoutOnResponse); - }); - var server = https.createServer(serverOptions, function(req, res) { - // just do nothing, we should get a timeout event. - req.setTimeout(50, function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); - }); - server.on('timeout', function(socket) { - socket.destroy(); - server.close(); - cb(); - }); - server.listen(common.PORT); - https.get({ - port: common.PORT, - rejectUnauthorized: false - }).on('error', function() {}); -}); - -test(function serverResponseTimeoutWithPipeline(cb) { - var caughtTimeout = ''; - process.on('exit', function() { - assert.equal(caughtTimeout, '/2'); - }); - var server = https.createServer(serverOptions, function(req, res) { - res.setTimeout(50, function() { - caughtTimeout += req.url; - }); - if (req.url === '/1') res.end(); - }); - server.on('timeout', function(socket) { - socket.destroy(); - server.close(); - cb(); - }); - server.listen(common.PORT); - var options = { - port: common.PORT, - allowHalfOpen: true, - rejectUnauthorized: false - }; - var c = tls.connect(options, function() { - c.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - c.write('GET /2 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - c.write('GET /3 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - }); -}); - -test(function idleTimeout(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - var caughtTimeoutOnServer = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(!caughtTimeoutOnResponse); - assert(caughtTimeoutOnServer); - }); - var server = https.createServer(serverOptions, function(req, res) { - req.on('timeout', function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); - res.end(); - }); - server.setTimeout(50, function(socket) { - caughtTimeoutOnServer = true; - socket.destroy(); - server.close(); - cb(); - }); - server.listen(common.PORT); - var options = { - port: common.PORT, - allowHalfOpen: true, - rejectUnauthorized: false - }; - tls.connect(options, function() { - this.write('GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n'); - // Keep-Alive - }); -}); diff --git a/test/simple/test-https-simple.js b/test/simple/test-https-simple.js deleted file mode 100644 index 552450c30..000000000 --- a/test/simple/test-https-simple.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var exec = require('child_process').exec; - -var https = require('https'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var reqCount = 0; -var body = 'hello world\n'; - -var server = https.createServer(options, function(req, res) { - reqCount++; - console.log('got request'); - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end(body); -}); - - -server.listen(common.PORT, function() { - var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/'; - console.error('executing %j', cmd); - exec(cmd, function(err, stdout, stderr) { - if (err) throw err; - common.error(common.inspect(stdout)); - assert.equal(body, stdout); - - // Do the same thing now without --insecure - // The connection should not be accepted. - var cmd = 'curl https://127.0.0.1:' + common.PORT + '/'; - console.error('executing %j', cmd); - exec(cmd, function(err, stdout, stderr) { - assert.ok(err); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(1, reqCount); -}); diff --git a/test/simple/test-https-socket-options.js b/test/simple/test-https-socket-options.js deleted file mode 100644 index 21b1118f7..000000000 --- a/test/simple/test-https-socket-options.js +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var exec = require('child_process').exec; - -var http = require('http'); -var https = require('https'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var body = 'hello world\n'; - -// Try first with http server - -var server_http = http.createServer(function(req, res) { - console.log('got HTTP request'); - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end(body); -}); - - -server_http.listen(common.PORT, function() { - var req = http.request({ - port: common.PORT, - rejectUnauthorized: false - }, function(res) { - server_http.close(); - res.resume(); - }); - // These methods should exist on the request and get passed down to the socket - req.setNoDelay(true); - req.setTimeout(1000, function() { }); - req.setSocketKeepAlive(true, 1000); - req.end(); -}); - -// Then try https server (requires functions to be mirroed in tls.js's CryptoStream) - -var server_https = https.createServer(options, function(req, res) { - console.log('got HTTPS request'); - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end(body); -}); - -server_https.listen(common.PORT+1, function() { - var req = https.request({ - port: common.PORT + 1, - rejectUnauthorized: false - }, function(res) { - server_https.close(); - res.resume(); - }); - // These methods should exist on the request and get passed down to the socket - req.setNoDelay(true); - req.setTimeout(1000, function() { }); - req.setSocketKeepAlive(true, 1000); - req.end(); -}); diff --git a/test/simple/test-https-strict.js b/test/simple/test-https-strict.js deleted file mode 100644 index 9cd763f7a..000000000 --- a/test/simple/test-https-strict.js +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -// disable strict server certificate validation by the client -process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var path = require('path'); -var https = require('https'); - -function file(fname) { - return path.resolve(common.fixturesDir, 'keys', fname); -} - -function read(fname) { - return fs.readFileSync(file(fname)); -} - -// key1 is signed by ca1. -var key1 = read('agent1-key.pem'); -var cert1 = read('agent1-cert.pem'); - -// key2 has a self signed cert -var key2 = read('agent2-key.pem'); -var cert2 = read('agent2-cert.pem'); - -// key3 is signed by ca2. -var key3 = read('agent3-key.pem'); -var cert3 = read('agent3-cert.pem'); - -var ca1 = read('ca1-cert.pem'); -var ca2 = read('ca2-cert.pem'); - -// different agents to use different CA lists. -// this api is beyond bad. -var agent0 = new https.Agent(); -var agent1 = new https.Agent({ ca: [ca1] }); -var agent2 = new https.Agent({ ca: [ca2] }); -var agent3 = new https.Agent({ ca: [ca1, ca2] }); - -var options1 = { - key: key1, - cert: cert1 -}; - -var options2 = { - key: key2, - cert: cert2 -}; - -var options3 = { - key: key3, - cert: cert3 -}; - -var server1 = server(options1); -var server2 = server(options2); -var server3 = server(options3); - -var listenWait = 0; - -var port = common.PORT; -var port1 = port++; -var port2 = port++; -var port3 = port++; -server1.listen(port1, listening()); -server2.listen(port2, listening()); -server3.listen(port3, listening()); - -var responseErrors = {}; -var expectResponseCount = 0; -var responseCount = 0; -var pending = 0; - - - -function server(options, port) { - var s = https.createServer(options, handler); - s.requests = []; - s.expectCount = 0; - return s; -} - -function handler(req, res) { - this.requests.push(req.url); - res.statusCode = 200; - res.setHeader('foo', 'bar'); - res.end('hello, world\n'); -} - -function listening() { - listenWait++; - return function() { - listenWait--; - if (listenWait === 0) { - allListening(); - } - } -} - -function makeReq(path, port, error, host, ca) { - pending++; - var options = { - port: port, - path: path, - ca: ca - }; - var whichCa = 0; - if (!ca) { - options.agent = agent0; - } else { - if (!Array.isArray(ca)) ca = [ca]; - if (-1 !== ca.indexOf(ca1) && -1 !== ca.indexOf(ca2)) { - options.agent = agent3; - } else if (-1 !== ca.indexOf(ca1)) { - options.agent = agent1; - } else if (-1 !== ca.indexOf(ca2)) { - options.agent = agent2; - } else { - options.agent = agent0; - } - } - - if (host) { - options.headers = { host: host } - } - var req = https.get(options); - expectResponseCount++; - var server = port === port1 ? server1 - : port === port2 ? server2 - : port === port3 ? server3 - : null; - - if (!server) throw new Error('invalid port: '+port); - server.expectCount++; - - req.on('response', function(res) { - responseCount++; - assert.equal(res.connection.authorizationError, error); - responseErrors[path] = res.connection.authorizationError; - pending--; - if (pending === 0) { - server1.close(); - server2.close(); - server3.close(); - } - res.resume(); - }) -} - -function allListening() { - // ok, ready to start the tests! - - // server1: host 'agent1', signed by ca1 - makeReq('/inv1', port1, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); - makeReq('/inv1-ca1', port1, - 'Hostname/IP doesn\'t match certificate\'s altnames: ' + - '"Host: localhost. is not cert\'s CN: agent1"', - null, ca1); - makeReq('/inv1-ca1ca2', port1, - 'Hostname/IP doesn\'t match certificate\'s altnames: ' + - '"Host: localhost. is not cert\'s CN: agent1"', - null, [ca1, ca2]); - makeReq('/val1-ca1', port1, null, 'agent1', ca1); - makeReq('/val1-ca1ca2', port1, null, 'agent1', [ca1, ca2]); - makeReq('/inv1-ca2', port1, - 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca2); - - // server2: self-signed, host = 'agent2' - // doesn't matter that thename matches, all of these will error. - makeReq('/inv2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT'); - makeReq('/inv2-ca1', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', - 'agent2', ca1); - makeReq('/inv2-ca1ca2', port2, 'DEPTH_ZERO_SELF_SIGNED_CERT', - 'agent2', [ca1, ca2]); - - // server3: host 'agent3', signed by ca2 - makeReq('/inv3', port3, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); - makeReq('/inv3-ca2', port3, - 'Hostname/IP doesn\'t match certificate\'s altnames: ' + - '"Host: localhost. is not cert\'s CN: agent3"', - null, ca2); - makeReq('/inv3-ca1ca2', port3, - 'Hostname/IP doesn\'t match certificate\'s altnames: ' + - '"Host: localhost. is not cert\'s CN: agent3"', - null, [ca1, ca2]); - makeReq('/val3-ca2', port3, null, 'agent3', ca2); - makeReq('/val3-ca1ca2', port3, null, 'agent3', [ca1, ca2]); - makeReq('/inv3-ca1', port3, - 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'agent1', ca1); - -} - -process.on('exit', function() { - console.error(responseErrors); - assert.equal(server1.requests.length, server1.expectCount); - assert.equal(server2.requests.length, server2.expectCount); - assert.equal(server3.requests.length, server3.expectCount); - assert.equal(responseCount, expectResponseCount); -}); diff --git a/test/simple/test-https-timeout-server-2.js b/test/simple/test-https-timeout-server-2.js deleted file mode 100644 index 076a0ec26..000000000 --- a/test/simple/test-https-timeout-server-2.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) process.exit(); - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var net = require('net'); -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = https.createServer(options, assert.fail); - -server.on('secureConnection', function(cleartext) { - cleartext.setTimeout(50, function() { - cleartext.destroy(); - server.close(); - }); -}); - -server.listen(common.PORT, function() { - tls.connect({ - host: '127.0.0.1', - port: common.PORT, - rejectUnauthorized: false - }); -}); diff --git a/test/simple/test-https-timeout-server.js b/test/simple/test-https-timeout-server.js deleted file mode 100644 index 57d6c57b5..000000000 --- a/test/simple/test-https-timeout-server.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) process.exit(); - -var common = require('../common'); -var assert = require('assert'); -var https = require('https'); -var net = require('net'); -var tls = require('tls'); -var fs = require('fs'); - -var clientErrors = 0; - -process.on('exit', function() { - assert.equal(clientErrors, 1); -}); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), - handshakeTimeout: 50 -}; - -var server = https.createServer(options, assert.fail); - -server.on('clientError', function(err, conn) { - // Don't hesitate to update the asserts if the internal structure of - // the cleartext object ever changes. We're checking that the https.Server - // has closed the client connection. - assert.equal(conn._secureEstablished, false); - server.close(); - clientErrors++; -}); - -server.listen(common.PORT, function() { - net.connect({ host: '127.0.0.1', port: common.PORT }); -}); diff --git a/test/simple/test-https-timeout.js b/test/simple/test-https-timeout.js deleted file mode 100644 index 8b79204d4..000000000 --- a/test/simple/test-https-timeout.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var exec = require('child_process').exec; -var https = require('https'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -// a server that never replies -var server = https.createServer(options, function() { - console.log('Got request. Doing nothing.'); -}).listen(common.PORT, function() { - var req = https.request({ - host: 'localhost', - port: common.PORT, - path: '/', - method: 'GET', - rejectUnauthorized: false - }); - req.setTimeout(10); - req.end(); - - req.on('response', function(res) { - console.log('got response'); - }); - - req.on('socket', function() { - console.log('got a socket'); - - req.socket.on('connect', function() { - console.log('socket connected'); - }); - - setTimeout(function() { - throw new Error('Did not get timeout event'); - }, 200); - }); - - req.on('timeout', function() { - console.log('timeout occurred outside'); - req.destroy(); - server.close(); - process.exit(0); - }); -}); diff --git a/test/simple/test-https-truncate.js b/test/simple/test-https-truncate.js deleted file mode 100644 index 889f91682..000000000 --- a/test/simple/test-https-truncate.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var https = require('https'); -var path = require('path'); - -var resultFile = path.resolve(common.tmpDir, 'result'); - -var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); - -var PORT = common.PORT; - -// number of bytes discovered empirically to trigger the bug -var data = new Buffer(1024 * 32 + 1); - -httpsTest(); - -function httpsTest() { - var sopt = { key: key, cert: cert }; - - var server = https.createServer(sopt, function(req, res) { - res.setHeader('content-length', data.length); - res.end(data); - server.close(); - }); - - server.listen(PORT, function() { - var opts = { port: PORT, rejectUnauthorized: false }; - https.get(opts).on('response', function(res) { - test(res); - }); - }); -} - - -function test(res) { - res.on('end', function() { - assert.equal(res._readableState.length, 0); - assert.equal(bytes, data.length); - console.log('ok'); - }); - - // Pause and then resume on each chunk, to ensure that there will be - // a lone byte hanging out at the very end. - var bytes = 0; - res.on('data', function(chunk) { - bytes += chunk.length; - this.pause(); - setTimeout(this.resume.bind(this)); - }); -} diff --git a/test/simple/test-init.js b/test/simple/test-init.js deleted file mode 100644 index 139df7f58..000000000 --- a/test/simple/test-init.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -(function() { - var assert = require('assert'), - child = require('child_process'), - util = require('util'), - common = require('../common'); - if (process.env['TEST_INIT']) { - util.print('Loaded successfully!'); - } else { - // change CWD as we do this test so its not dependant on current CWD - // being in the test folder - process.chdir(__dirname); - - // slow but simple - var envCopy = JSON.parse(JSON.stringify(process.env)); - envCopy.TEST_INIT = 1; - - child.exec(process.execPath + ' test-init', {env: envCopy}, - function(err, stdout, stderr) { - assert.equal(stdout, 'Loaded successfully!', - '`node test-init` failed!'); - }); - child.exec(process.execPath + ' test-init.js', {env: envCopy}, - function(err, stdout, stderr) { - assert.equal(stdout, 'Loaded successfully!', - '`node test-init.js` failed!'); - }); - - // test-init-index is in fixtures dir as requested by ry, so go there - process.chdir(common.fixturesDir); - - child.exec(process.execPath + ' test-init-index', {env: envCopy}, - function(err, stdout, stderr) { - assert.equal(stdout, 'Loaded successfully!', - '`node test-init-index failed!'); - }); - - // ensures that `node fs` does not mistakenly load the native 'fs' module - // instead of the desired file and that the fs module loads as - // expected in node - process.chdir(common.fixturesDir + '/test-init-native/'); - - child.exec(process.execPath + ' fs', {env: envCopy}, - function(err, stdout, stderr) { - assert.equal(stdout, 'fs loaded successfully', - '`node fs` failed!'); - }); - } -})(); diff --git a/test/simple/test-listen-fd-cluster.js b/test/simple/test-listen-fd-cluster.js deleted file mode 100644 index 0d6d7748a..000000000 --- a/test/simple/test-listen-fd-cluster.js +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var PORT = common.PORT; -var spawn = require('child_process').spawn; -var cluster = require('cluster'); - -console.error('Cluster listen fd test', process.argv.slice(2)); - -if (process.platform === 'win32') { - console.error('This test is disabled on windows.'); - return; -} - -switch (process.argv[2]) { - case 'master': return master(); - case 'worker': return worker(); - case 'parent': return parent(); - default: return test(); -} - -// spawn the parent, and listen for it to tell us the pid of the cluster. -// WARNING: This is an example of listening on some arbitrary FD number -// that has already been bound elsewhere in advance. However, binding -// server handles to stdio fd's is NOT a good or reliable way to do -// concurrency in HTTP servers! Use the cluster module, or if you want -// a more low-level approach, use child process IPC manually. -function test() { - var parent = spawn(process.execPath, [__filename, 'parent'], { - stdio: [ 0, 'pipe', 2 ] - }); - var json = ''; - parent.stdout.on('data', function(c) { - json += c.toString(); - if (json.indexOf('\n') !== -1) next(); - }); - function next() { - console.error('output from parent = %s', json); - var cluster = JSON.parse(json); - // now make sure that we can request to the worker, then kill it. - http.get({ - server: 'localhost', - port: PORT, - path: '/', - }).on('response', function (res) { - var s = ''; - res.on('data', function(c) { - s += c.toString(); - }); - res.on('end', function() { - // kill the worker before we start doing asserts. - // it's really annoying when tests leave orphans! - parent.kill(); - process.kill(cluster.master, 'SIGKILL'); - - assert.equal(s, 'hello from worker\n'); - assert.equal(res.statusCode, 200); - console.log('ok'); - }); - }) - } -} - -function parent() { - console.error('about to listen in parent'); - var server = net.createServer(function(conn) { - console.error('connection on parent'); - conn.end('hello from parent\n'); - }).listen(PORT, function() { - console.error('server listening on %d', PORT); - - var spawn = require('child_process').spawn; - var master = spawn(process.execPath, [__filename, 'master'], { - stdio: [ 0, 1, 2, server._handle ], - detached: true - }); - - // Now close the parent, so that the master is the only thing - // referencing that handle. Note that connections will still - // be accepted, because the master has the fd open. - server.close(); - - master.on('exit', function(code) { - console.error('master exited', code); - }); - - master.on('close', function() { - console.error('master closed'); - }); - console.error('master spawned'); - }); -} - -function master() { - console.error('in master, spawning worker'); - cluster.setupMaster({ - args: [ 'worker' ] - }); - var worker = cluster.fork(); - console.log('%j\n', { master: process.pid, worker: worker.pid }); -} - - -function worker() { - console.error('worker, about to create server and listen on fd=3'); - // start a server on fd=3 - http.createServer(function(req, res) { - console.error('request on worker'); - console.error('%s %s', req.method, req.url, req.headers); - res.end('hello from worker\n'); - }).listen({ fd: 3 }, function() { - console.error('worker listening on fd=3'); - }); -} diff --git a/test/simple/test-listen-fd-detached-inherit.js b/test/simple/test-listen-fd-detached-inherit.js deleted file mode 100644 index dabc46cd3..000000000 --- a/test/simple/test-listen-fd-detached-inherit.js +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var PORT = common.PORT; -var spawn = require('child_process').spawn; - -if (process.platform === 'win32') { - console.error('This test is disabled on windows.'); - return; -} - -switch (process.argv[2]) { - case 'child': return child(); - case 'parent': return parent(); - default: return test(); -} - -// spawn the parent, and listen for it to tell us the pid of the child. -// WARNING: This is an example of listening on some arbitrary FD number -// that has already been bound elsewhere in advance. However, binding -// server handles to stdio fd's is NOT a good or reliable way to do -// concurrency in HTTP servers! Use the cluster module, or if you want -// a more low-level approach, use child process IPC manually. -function test() { - var parent = spawn(process.execPath, [__filename, 'parent'], { - stdio: [ 0, 'pipe', 2 ] - }); - var json = ''; - parent.stdout.on('data', function(c) { - json += c.toString(); - if (json.indexOf('\n') !== -1) next(); - }); - function next() { - console.error('output from parent = %s', json); - var child = JSON.parse(json); - // now make sure that we can request to the child, then kill it. - http.get({ - server: 'localhost', - port: PORT, - path: '/', - }).on('response', function (res) { - var s = ''; - res.on('data', function(c) { - s += c.toString(); - }); - res.on('end', function() { - // kill the child before we start doing asserts. - // it's really annoying when tests leave orphans! - process.kill(child.pid, 'SIGKILL'); - try { - parent.kill(); - } catch (e) {} - - assert.equal(s, 'hello from child\n'); - assert.equal(res.statusCode, 200); - }); - }) - } -} - -// Listen on PORT, and then pass the handle to the detached child. -// Then output the child's pid, and immediately exit. -function parent() { - var server = net.createServer(function(conn) { - throw new Error('Should not see connections on parent'); - conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n'); - }).listen(PORT, function() { - console.error('server listening on %d', PORT); - - var child = spawn(process.execPath, [__filename, 'child'], { - stdio: [ 0, 1, 2, server._handle ], - detached: true - }); - - console.log('%j\n', { pid: child.pid }); - - // Now close the parent, so that the child is the only thing - // referencing that handle. Note that connections will still - // be accepted, because the child has the fd open, but the parent - // will exit gracefully. - server.close(); - child.unref(); - }); -} - -// Run as a child of the parent() mode. -function child() { - // start a server on fd=3 - http.createServer(function(req, res) { - console.error('request on child'); - console.error('%s %s', req.method, req.url, req.headers); - res.end('hello from child\n'); - }).listen({ fd: 3 }, function() { - console.error('child listening on fd=3'); - }); -} - diff --git a/test/simple/test-listen-fd-detached.js b/test/simple/test-listen-fd-detached.js deleted file mode 100644 index 3d98abeac..000000000 --- a/test/simple/test-listen-fd-detached.js +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var PORT = common.PORT; -var spawn = require('child_process').spawn; - -if (process.platform === 'win32') { - console.error('This test is disabled on windows.'); - return; -} - -switch (process.argv[2]) { - case 'child': return child(); - case 'parent': return parent(); - default: return test(); -} - -// spawn the parent, and listen for it to tell us the pid of the child. -// WARNING: This is an example of listening on some arbitrary FD number -// that has already been bound elsewhere in advance. However, binding -// server handles to stdio fd's is NOT a good or reliable way to do -// concurrency in HTTP servers! Use the cluster module, or if you want -// a more low-level approach, use child process IPC manually. -function test() { - var parent = spawn(process.execPath, [__filename, 'parent'], { - stdio: [ 0, 'pipe', 2 ] - }); - var json = ''; - parent.stdout.on('data', function(c) { - json += c.toString(); - if (json.indexOf('\n') !== -1) next(); - }); - function next() { - console.error('output from parent = %s', json); - var child = JSON.parse(json); - // now make sure that we can request to the child, then kill it. - http.get({ - server: 'localhost', - port: PORT, - path: '/', - }).on('response', function (res) { - var s = ''; - res.on('data', function(c) { - s += c.toString(); - }); - res.on('end', function() { - // kill the child before we start doing asserts. - // it's really annoying when tests leave orphans! - process.kill(child.pid, 'SIGKILL'); - try { - parent.kill(); - } catch (e) {} - - assert.equal(s, 'hello from child\n'); - assert.equal(res.statusCode, 200); - }); - }) - } -} - -function parent() { - var server = net.createServer(function(conn) { - console.error('connection on parent'); - conn.end('hello from parent\n'); - }).listen(PORT, function() { - console.error('server listening on %d', PORT); - - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { - stdio: [ 'ignore', 'ignore', 'ignore', server._handle ], - detached: true - }); - - console.log('%j\n', { pid: child.pid }); - - // Now close the parent, so that the child is the only thing - // referencing that handle. Note that connections will still - // be accepted, because the child has the fd open, but the parent - // will exit gracefully. - server.close(); - child.unref(); - }); -} - -function child() { - // start a server on fd=3 - http.createServer(function(req, res) { - console.error('request on child'); - console.error('%s %s', req.method, req.url, req.headers); - res.end('hello from child\n'); - }).listen({ fd: 3 }, function() { - console.error('child listening on fd=3'); - }); -} - diff --git a/test/simple/test-listen-fd-ebadf.js b/test/simple/test-listen-fd-ebadf.js deleted file mode 100644 index 6c0f20ae4..000000000 --- a/test/simple/test-listen-fd-ebadf.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var gotError = 0; - -process.on('exit', function() { - assert.equal(gotError, 2); -}); - -net.createServer(assert.fail).listen({fd:2}).on('error', onError); -net.createServer(assert.fail).listen({fd:42}).on('error', onError); - -function onError(ex) { - assert.equal(ex.code, 'EINVAL'); - gotError++; -} diff --git a/test/simple/test-listen-fd-server.js b/test/simple/test-listen-fd-server.js deleted file mode 100644 index 8f3454fbb..000000000 --- a/test/simple/test-listen-fd-server.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var PORT = common.PORT; -var spawn = require('child_process').spawn; - -if (process.platform === 'win32') { - console.error('This test is disabled on windows.'); - return; -} - -switch (process.argv[2]) { - case 'child': return child(); - case 'parent': return parent(); - default: return test(); -} - -// spawn the parent, and listen for it to tell us the pid of the child. -// WARNING: This is an example of listening on some arbitrary FD number -// that has already been bound elsewhere in advance. However, binding -// server handles to stdio fd's is NOT a good or reliable way to do -// concurrency in HTTP servers! Use the cluster module, or if you want -// a more low-level approach, use child process IPC manually. -function test() { - var parent = spawn(process.execPath, [__filename, 'parent'], { - stdio: [ 0, 'pipe', 2 ] - }); - var json = ''; - parent.stdout.on('data', function(c) { - json += c.toString(); - if (json.indexOf('\n') !== -1) next(); - }); - function next() { - console.error('output from parent = %s', json); - var child = JSON.parse(json); - // now make sure that we can request to the child, then kill it. - http.get({ - server: 'localhost', - port: PORT, - path: '/', - }).on('response', function (res) { - var s = ''; - res.on('data', function(c) { - s += c.toString(); - }); - res.on('end', function() { - // kill the child before we start doing asserts. - // it's really annoying when tests leave orphans! - process.kill(child.pid, 'SIGKILL'); - try { - parent.kill(); - } catch (e) {} - - assert.equal(s, 'hello from child\n'); - assert.equal(res.statusCode, 200); - }); - }) - } -} - -function child() { - // start a server on fd=3 - http.createServer(function(req, res) { - console.error('request on child'); - console.error('%s %s', req.method, req.url, req.headers); - res.end('hello from child\n'); - }).listen({ fd: 3 }, function() { - console.error('child listening on fd=3'); - }); -} - -function parent() { - var server = net.createServer(function(conn) { - console.error('connection on parent'); - conn.end('hello from parent\n'); - }).listen(PORT, function() { - console.error('server listening on %d', PORT); - - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { - stdio: [ 0, 1, 2, server._handle ] - }); - - console.log('%j\n', { pid: child.pid }); - - // Now close the parent, so that the child is the only thing - // referencing that handle. Note that connections will still - // be accepted, because the child has the fd open. - server.close(); - - child.on('exit', function(code) { - console.error('child exited', code); - }); - - child.on('close', function() { - console.error('child closed'); - }); - console.error('child spawned'); - }); -} diff --git a/test/simple/test-memory-usage-emfile.js b/test/simple/test-memory-usage-emfile.js deleted file mode 100644 index aaed89953..000000000 --- a/test/simple/test-memory-usage-emfile.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); - -var files = []; - -while (files.length < 256) - files.push(fs.openSync(__filename, 'r')); - -var r = process.memoryUsage(); -console.log(common.inspect(r)); -assert.equal(true, r['rss'] > 0); diff --git a/test/simple/test-memory-usage.js b/test/simple/test-memory-usage.js deleted file mode 100644 index 0df17420c..000000000 --- a/test/simple/test-memory-usage.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var r = process.memoryUsage(); -console.log(common.inspect(r)); -assert.equal(true, r['rss'] > 0); diff --git a/test/simple/test-microtask-queue-integration-domain.js b/test/simple/test-microtask-queue-integration-domain.js deleted file mode 100644 index 2197bf921..000000000 --- a/test/simple/test-microtask-queue-integration-domain.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); - -var implementations = [ - function (fn) { - Promise.resolve().then(fn); - }, - function (fn) { - var obj = {}; - - Object.observe(obj, fn); - - obj.a = 1; - } -]; - -var expected = 0; -var done = 0; - -process.on('exit', function () { - assert.equal(done, expected); -}); - -function test (scheduleMicrotask) { - var nextTickCalled = false; - expected++; - - scheduleMicrotask(function () { - process.nextTick(function () { - nextTickCalled = true; - }); - - setTimeout(function () { - assert(nextTickCalled); - done++; - }, 0); - }); -} - -// first tick case -implementations.forEach(test); - -// tick callback case -setTimeout(function () { - implementations.forEach(function (impl) { - process.nextTick(test.bind(null, impl)); - }); -}, 0); diff --git a/test/simple/test-microtask-queue-integration.js b/test/simple/test-microtask-queue-integration.js deleted file mode 100644 index af0154847..000000000 --- a/test/simple/test-microtask-queue-integration.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var implementations = [ - function (fn) { - Promise.resolve().then(fn); - }, - function (fn) { - var obj = {}; - - Object.observe(obj, fn); - - obj.a = 1; - } -]; - -var expected = 0; -var done = 0; - -process.on('exit', function () { - assert.equal(done, expected); -}); - -function test (scheduleMicrotask) { - var nextTickCalled = false; - expected++; - - scheduleMicrotask(function () { - process.nextTick(function () { - nextTickCalled = true; - }); - - setTimeout(function () { - assert(nextTickCalled); - done++; - }, 0); - }); -} - -// first tick case -implementations.forEach(test); - -// tick callback case -setTimeout(function () { - implementations.forEach(function (impl) { - process.nextTick(test.bind(null, impl)); - }); -}, 0); diff --git a/test/simple/test-microtask-queue-run-domain.js b/test/simple/test-microtask-queue-run-domain.js deleted file mode 100644 index 2b3b76315..000000000 --- a/test/simple/test-microtask-queue-run-domain.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); - -function enqueueMicrotask(fn) { - Promise.resolve().then(fn); -} - -var done = 0; - -process.on('exit', function() { - assert.equal(done, 2); -}); - -// no nextTick, microtask -setTimeout(function() { - enqueueMicrotask(function() { - done++; - }); -}, 0); - - -// no nextTick, microtask with nextTick -setTimeout(function() { - var called = false; - - enqueueMicrotask(function() { - process.nextTick(function() { - called = true; - }); - }); - - setTimeout(function() { - if (called) - done++; - }, 0); - -}, 0); diff --git a/test/simple/test-microtask-queue-run-immediate-domain.js b/test/simple/test-microtask-queue-run-immediate-domain.js deleted file mode 100644 index 8f95fadd5..000000000 --- a/test/simple/test-microtask-queue-run-immediate-domain.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var domain = require('domain'); - -function enqueueMicrotask(fn) { - Promise.resolve().then(fn); -} - -var done = 0; - -process.on('exit', function() { - assert.equal(done, 2); -}); - -// no nextTick, microtask -setImmediate(function() { - enqueueMicrotask(function() { - done++; - }); -}); - - -// no nextTick, microtask with nextTick -setImmediate(function() { - var called = false; - - enqueueMicrotask(function() { - process.nextTick(function() { - called = true; - }); - }); - - setImmediate(function() { - if (called) - done++; - }); - -}); diff --git a/test/simple/test-microtask-queue-run-immediate.js b/test/simple/test-microtask-queue-run-immediate.js deleted file mode 100644 index b5423eb6b..000000000 --- a/test/simple/test-microtask-queue-run-immediate.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -function enqueueMicrotask(fn) { - Promise.resolve().then(fn); -} - -var done = 0; - -process.on('exit', function() { - assert.equal(done, 2); -}); - -// no nextTick, microtask -setImmediate(function() { - enqueueMicrotask(function() { - done++; - }); -}); - - -// no nextTick, microtask with nextTick -setImmediate(function() { - var called = false; - - enqueueMicrotask(function() { - process.nextTick(function() { - called = true; - }); - }); - - setImmediate(function() { - if (called) - done++; - }); - -}); diff --git a/test/simple/test-microtask-queue-run.js b/test/simple/test-microtask-queue-run.js deleted file mode 100644 index c4138454f..000000000 --- a/test/simple/test-microtask-queue-run.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -function enqueueMicrotask(fn) { - Promise.resolve().then(fn); -} - -var done = 0; - -process.on('exit', function() { - assert.equal(done, 2); -}); - -// no nextTick, microtask -setTimeout(function() { - enqueueMicrotask(function() { - done++; - }); -}, 0); - - -// no nextTick, microtask with nextTick -setTimeout(function() { - var called = false; - - enqueueMicrotask(function() { - process.nextTick(function() { - called = true; - }); - }); - - setTimeout(function() { - if (called) - done++; - }, 0); - -}, 0); diff --git a/test/simple/test-mkdir-rmdir.js b/test/simple/test-mkdir-rmdir.js deleted file mode 100644 index 73534555c..000000000 --- a/test/simple/test-mkdir-rmdir.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var dirname = path.dirname(__filename); -var d = path.join(common.tmpDir, 'dir'); - -var mkdir_error = false; -var rmdir_error = false; - -fs.mkdir(d, 0666, function(err) { - if (err) { - console.log('mkdir error: ' + err.message); - mkdir_error = true; - } else { - fs.mkdir(d, 0666, function(err) { - console.log('expect EEXIST error: ', err); - assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); - assert.equal(err.code, 'EEXIST', 'got EEXIST code'); - assert.equal(err.path, d, 'got proper path for EEXIST'); - - console.log('mkdir okay!'); - fs.rmdir(d, function(err) { - if (err) { - console.log('rmdir error: ' + err.message); - rmdir_error = true; - } else { - console.log('rmdir okay!'); - } - }); - }); - } -}); - -process.on('exit', function() { - assert.equal(false, mkdir_error); - assert.equal(false, rmdir_error); - console.log('exit'); -}); diff --git a/test/simple/test-module-globalpaths-nodepath.js b/test/simple/test-module-globalpaths-nodepath.js deleted file mode 100644 index c99b6763b..000000000 --- a/test/simple/test-module-globalpaths-nodepath.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var module = require('module'); - -var isWindows = process.platform === 'win32'; - -var partA, partB; - -if (isWindows) { - partA = 'C:\\Users\\Rocko Artischocko\\AppData\\Roaming\\npm'; - partB = 'C:\\Program Files (x86)\\nodejs\\'; - process.env['NODE_PATH'] = partA + ';' + partB; -} else { - partA = '/usr/test/lib/node_modules'; - partB = '/usr/test/lib/node'; - process.env['NODE_PATH'] = partA + ':' + partB; -} - -module._initPaths(); - -assert.ok(module.globalPaths.indexOf(partA) !== -1); -assert.ok(module.globalPaths.indexOf(partB) !== -1); - -assert.ok(Array.isArray(module.globalPaths)); \ No newline at end of file diff --git a/test/simple/test-module-loading-error.js b/test/simple/test-module-loading-error.js deleted file mode 100644 index beddb5d37..000000000 --- a/test/simple/test-module-loading-error.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -common.debug('load test-module-loading-error.js'); - -var error_desc = { - win32: '%1 is not a valid Win32 application', - linux: 'file too short', - sunos: 'unknown file type' -}; - -var dlerror_msg = error_desc[process.platform]; - -if (!dlerror_msg) { - console.error('Skipping test, platform not supported.'); - process.exit(); -} - -try { - require('../fixtures/module-loading-error.node'); -} catch (e) { - assert.notEqual(e.toString().indexOf(dlerror_msg), -1); -} - -try { - require(); -} catch (e) { - assert.notEqual(e.toString().indexOf('missing path'), -1); -} - -try { - require({}); -} catch (e) { - assert.notEqual(e.toString().indexOf('path must be a string'), -1); -} diff --git a/test/simple/test-module-loading.js b/test/simple/test-module-loading.js deleted file mode 100644 index 8687c3b98..000000000 --- a/test/simple/test-module-loading.js +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -common.debug('load test-module-loading.js'); - -// assert that this is the main module. -assert.equal(require.main.id, '.', 'main module should have id of \'.\''); -assert.equal(require.main, module, 'require.main should === module'); -assert.equal(process.mainModule, module, - 'process.mainModule should === module'); -// assert that it's *not* the main module in the required module. -require('../fixtures/not-main-module.js'); - -// require a file with a request that includes the extension -var a_js = require('../fixtures/a.js'); -assert.equal(42, a_js.number); - -// require a file without any extensions -var foo_no_ext = require('../fixtures/foo'); -assert.equal('ok', foo_no_ext.foo); - -var a = require('../fixtures/a'); -var c = require('../fixtures/b/c'); -var d = require('../fixtures/b/d'); -var d2 = require('../fixtures/b/d'); -// Absolute -var d3 = require(path.join(__dirname, '../fixtures/b/d')); -// Relative -var d4 = require('../fixtures/b/d'); - -assert.equal(false, false, 'testing the test program.'); - -assert.equal(true, common.indirectInstanceOf(a.A, Function)); -assert.equal('A', a.A()); - -assert.equal(true, common.indirectInstanceOf(a.C, Function)); -assert.equal('C', a.C()); - -assert.equal(true, common.indirectInstanceOf(a.D, Function)); -assert.equal('D', a.D()); - -assert.equal(true, common.indirectInstanceOf(d.D, Function)); -assert.equal('D', d.D()); - -assert.equal(true, common.indirectInstanceOf(d2.D, Function)); -assert.equal('D', d2.D()); - -assert.equal(true, common.indirectInstanceOf(d3.D, Function)); -assert.equal('D', d3.D()); - -assert.equal(true, common.indirectInstanceOf(d4.D, Function)); -assert.equal('D', d4.D()); - -assert.ok((new a.SomeClass) instanceof c.SomeClass); - -common.debug('test index.js modules ids and relative loading'); -var one = require('../fixtures/nested-index/one'), - two = require('../fixtures/nested-index/two'); -assert.notEqual(one.hello, two.hello); - -common.debug('test index.js in a folder with a trailing slash'); -var three = require('../fixtures/nested-index/three'), - threeFolder = require('../fixtures/nested-index/three/'), - threeIndex = require('../fixtures/nested-index/three/index.js'); -assert.equal(threeFolder, threeIndex); -assert.notEqual(threeFolder, three); - -common.debug('test package.json require() loading'); -assert.equal(require('../fixtures/packages/main').ok, 'ok', - 'Failed loading package'); -assert.equal(require('../fixtures/packages/main-index').ok, 'ok', - 'Failed loading package with index.js in main subdir'); - -common.debug('test cycles containing a .. path'); -var root = require('../fixtures/cycles/root'), - foo = require('../fixtures/cycles/folder/foo'); -assert.equal(root.foo, foo); -assert.equal(root.sayHello(), root.hello); - -common.debug('test node_modules folders'); -// asserts are in the fixtures files themselves, -// since they depend on the folder structure. -require('../fixtures/node_modules/foo'); - -common.debug('test name clashes'); -// this one exists and should import the local module -var my_path = require('./path'); -assert.ok(common.indirectInstanceOf(my_path.path_func, Function)); -// this one does not exist and should throw -assert.throws(function() { require('./utils')}); - -var errorThrown = false; -try { - require('../fixtures/throws_error'); -} catch (e) { - errorThrown = true; - assert.equal('blah', e.message); -} - -assert.equal(require('path').dirname(__filename), __dirname); - -common.debug('load custom file types with extensions'); -require.extensions['.test'] = function(module, filename) { - var content = fs.readFileSync(filename).toString(); - assert.equal('this is custom source\n', content); - content = content.replace('this is custom source', - 'exports.test = \'passed\''); - module._compile(content, filename); -}; - -assert.equal(require('../fixtures/registerExt').test, 'passed'); -// unknown extension, load as .js -assert.equal(require('../fixtures/registerExt.hello.world').test, 'passed'); - -common.debug('load custom file types that return non-strings'); -require.extensions['.test'] = function(module, filename) { - module.exports = { - custom: 'passed' - }; -}; - -assert.equal(require('../fixtures/registerExt2').custom, 'passed'); - -assert.equal(require('../fixtures/foo').foo, 'ok', - 'require module with no extension'); - -assert.throws(function() { - require.paths; -}, /removed/, 'Accessing require.paths should throw.'); - -// Should not attempt to load a directory -try { - require('../fixtures/empty'); -} catch (err) { - assert.equal(err.message, 'Cannot find module \'../fixtures/empty\''); -} - -// Check load order is as expected -common.debug('load order'); - -var loadOrder = '../fixtures/module-load-order/', - msg = 'Load order incorrect.'; - -require.extensions['.reg'] = require.extensions['.js']; -require.extensions['.reg2'] = require.extensions['.js']; - -assert.equal(require(loadOrder + 'file1').file1, 'file1', msg); -assert.equal(require(loadOrder + 'file2').file2, 'file2.js', msg); -try { - require(loadOrder + 'file3'); -} catch (e) { - // Not a real .node module, but we know we require'd the right thing. - assert.ok(e.message.replace(/\\/g, '/').match(/file3\.node/)); -} -assert.equal(require(loadOrder + 'file4').file4, 'file4.reg', msg); -assert.equal(require(loadOrder + 'file5').file5, 'file5.reg2', msg); -assert.equal(require(loadOrder + 'file6').file6, 'file6/index.js', msg); -try { - require(loadOrder + 'file7'); -} catch (e) { - assert.ok(e.message.replace(/\\/g, '/').match(/file7\/index\.node/)); -} -assert.equal(require(loadOrder + 'file8').file8, 'file8/index.reg', msg); -assert.equal(require(loadOrder + 'file9').file9, 'file9/index.reg2', msg); - - -// make sure that module.require() is the same as -// doing require() inside of that module. -var parent = require('../fixtures/module-require/parent/'); -var child = require('../fixtures/module-require/child/'); -assert.equal(child.loaded, parent.loaded); - - -// #1357 Loading JSON files with require() -var json = require('../fixtures/packages/main/package.json'); -assert.deepEqual(json, { - name: 'package-name', - version: '1.2.3', - main: 'package-main-module' -}); - - -// now verify that module.children contains all the different -// modules that we've required, and that all of them contain -// the appropriate children, and so on. - -var children = module.children.reduce(function red(set, child) { - var id = path.relative(path.dirname(__dirname), child.id) - id = id.replace(/\\/g, '/'); - set[id] = child.children.reduce(red, {}); - return set; -}, {}); - -assert.deepEqual(children, { - 'common.js': {}, - 'fixtures/not-main-module.js': {}, - 'fixtures/a.js': { - 'fixtures/b/c.js': { - 'fixtures/b/d.js': {}, - 'fixtures/b/package/index.js': {} - } - }, - 'fixtures/foo': {}, - 'fixtures/nested-index/one/index.js': { - 'fixtures/nested-index/one/hello.js': {} - }, - 'fixtures/nested-index/two/index.js': { - 'fixtures/nested-index/two/hello.js': {} - }, - 'fixtures/nested-index/three.js': {}, - 'fixtures/nested-index/three/index.js': {}, - 'fixtures/packages/main/package-main-module.js': {}, - 'fixtures/packages/main-index/package-main-module/index.js': {}, - 'fixtures/cycles/root.js': { - 'fixtures/cycles/folder/foo.js': {} - }, - 'fixtures/node_modules/foo.js': { - 'fixtures/node_modules/baz/index.js': { - 'fixtures/node_modules/bar.js': {}, - 'fixtures/node_modules/baz/node_modules/asdf.js': {} - } - }, - 'simple/path.js': {}, - 'fixtures/throws_error.js': {}, - 'fixtures/registerExt.test': {}, - 'fixtures/registerExt.hello.world': {}, - 'fixtures/registerExt2.test': {}, - 'fixtures/empty.js': {}, - 'fixtures/module-load-order/file1': {}, - 'fixtures/module-load-order/file2.js': {}, - 'fixtures/module-load-order/file3.node': {}, - 'fixtures/module-load-order/file4.reg': {}, - 'fixtures/module-load-order/file5.reg2': {}, - 'fixtures/module-load-order/file6/index.js': {}, - 'fixtures/module-load-order/file7/index.node': {}, - 'fixtures/module-load-order/file8/index.reg': {}, - 'fixtures/module-load-order/file9/index.reg2': {}, - 'fixtures/module-require/parent/index.js': { - 'fixtures/module-require/child/index.js': { - 'fixtures/module-require/child/node_modules/target.js': {} - } - }, - 'fixtures/packages/main/package.json': {} -}); - - -// require() must take string, and must be truthy -assert.throws(function() { - console.error('require non-string'); - require({ foo: 'bar' }); -}, 'path must be a string'); - -assert.throws(function() { - console.error('require empty string'); - require(''); -}, 'missing path'); - -process.on('exit', function() { - assert.ok(common.indirectInstanceOf(a.A, Function)); - assert.equal('A done', a.A()); - - assert.ok(common.indirectInstanceOf(a.C, Function)); - assert.equal('C done', a.C()); - - assert.ok(common.indirectInstanceOf(a.D, Function)); - assert.equal('D done', a.D()); - - assert.ok(common.indirectInstanceOf(d.D, Function)); - assert.equal('D done', d.D()); - - assert.ok(common.indirectInstanceOf(d2.D, Function)); - assert.equal('D done', d2.D()); - - assert.equal(true, errorThrown); - - console.log('exit'); -}); - - -// #1440 Loading files with a byte order marker. -assert.equal(42, require('../fixtures/utf8-bom.js')); -assert.equal(42, require('../fixtures/utf8-bom.json')); diff --git a/test/simple/test-module-nodemodulepaths.js b/test/simple/test-module-nodemodulepaths.js deleted file mode 100644 index 3d48d99ab..000000000 --- a/test/simple/test-module-nodemodulepaths.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var module = require('module'); - -var isWindows = process.platform === 'win32'; - -var file, delimiter, paths; - -if (isWindows) { - file = 'C:\\Users\\Rocko Artischocko\\node_stuff\\foo'; - delimiter = '\\' -} else { - file = '/usr/test/lib/node_modules/npm/foo'; - delimiter = '/' -} - -paths = module._nodeModulePaths(file); - -assert.ok(paths.indexOf(file + delimiter + 'node_modules') !== -1); -assert.ok(Array.isArray(paths)); \ No newline at end of file diff --git a/test/simple/test-net-GH-5504.js b/test/simple/test-net-GH-5504.js deleted file mode 100644 index 0e87c8210..000000000 --- a/test/simple/test-net-GH-5504.js +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// this test only fails with CentOS 6.3 using kernel version 2.6.32 -// On other linuxes and darwin, the `read` call gets an ECONNRESET in -// that case. On sunos, the `write` call fails with EPIPE. -// -// However, old CentOS will occasionally send an EOF instead of a -// ECONNRESET or EPIPE when the client has been destroyed abruptly. -// -// Make sure we don't keep trying to write or read more in that case. - -switch (process.argv[2]) { - case 'server': return server(); - case 'client': return client(); - case undefined: return parent(); - default: throw new Error('wtf'); -} - -function server() { - var net = require('net'); - var content = new Buffer(64 * 1024 * 1024); - content.fill('#'); - net.createServer(function(socket) { - this.close(); - socket.on('end', function() { - console.error('end'); - }); - socket.on('_socketEnd', function() { - console.error('_socketEnd'); - }); - socket.write(content); - }).listen(common.PORT, function() { - console.log('listening'); - }); -} - -function client() { - var net = require('net'); - var client = net.connect({ - host: 'localhost', - port: common.PORT - }, function() { - client.destroy(); - }); -} - -function parent() { - var spawn = require('child_process').spawn; - var node = process.execPath; - var assert = require('assert'); - var serverExited = false; - var clientExited = false; - var serverListened = false; - var opt = { - env: { - NODE_DEBUG: 'net', - NODE_COMMON_PORT: process.env.NODE_COMMON_PORT, - } - }; - - process.on('exit', function() { - assert(serverExited); - assert(clientExited); - assert(serverListened); - console.log('ok'); - }); - - setTimeout(function() { - if (s) s.kill(); - if (c) c.kill(); - setTimeout(function() { - throw new Error('hang'); - }); - }, 4000).unref(); - - var s = spawn(node, [__filename, 'server'], opt); - var c; - - wrap(s.stderr, process.stderr, 'SERVER 2>'); - wrap(s.stdout, process.stdout, 'SERVER 1>'); - s.on('exit', function(c) { - console.error('server exited', c); - serverExited = true; - }); - - s.stdout.once('data', function() { - serverListened = true; - c = spawn(node, [__filename, 'client']); - wrap(c.stderr, process.stderr, 'CLIENT 2>'); - wrap(c.stdout, process.stdout, 'CLIENT 1>'); - c.on('exit', function(c) { - console.error('client exited', c); - clientExited = true; - }); - }); - - function wrap(inp, out, w) { - inp.setEncoding('utf8'); - inp.on('data', function(c) { - c = c.trim(); - if (!c) return; - out.write(w + c.split('\n').join('\n' + w) + '\n'); - }); - } -} - diff --git a/test/simple/test-net-after-close.js b/test/simple/test-net-after-close.js deleted file mode 100644 index 2f3d4c379..000000000 --- a/test/simple/test-net-after-close.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var closed = false; - -var server = net.createServer(function(s) { - console.error('SERVER: got connection'); - s.end(); -}); - -server.listen(common.PORT, function() { - var c = net.createConnection(common.PORT); - c.on('close', function() { - console.error('connection closed'); - assert.strictEqual(c._handle, null); - closed = true; - assert.doesNotThrow(function() { - c.setNoDelay(); - c.setKeepAlive(); - c.bufferSize; - c.pause(); - c.resume(); - c.address(); - c.remoteAddress; - c.remotePort; - }); - server.close(); - }); -}); - -process.on('exit', function() { - assert(closed); -}); diff --git a/test/simple/test-net-better-error-messages-listen-path.js b/test/simple/test-net-better-error-messages-listen-path.js deleted file mode 100644 index fcc3062a8..000000000 --- a/test/simple/test-net-better-error-messages-listen-path.js +++ /dev/null @@ -1,9 +0,0 @@ -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var fp = '/blah/fadfa'; -var server = net.createServer(assert.fail); -server.listen(fp, assert.fail); -server.on('error', common.mustCall(function(e) { - assert.equal(e.address, fp) -})); diff --git a/test/simple/test-net-better-error-messages-listen.js b/test/simple/test-net-better-error-messages-listen.js deleted file mode 100644 index 9c7766bd4..000000000 --- a/test/simple/test-net-better-error-messages-listen.js +++ /dev/null @@ -1,11 +0,0 @@ -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var server = net.createServer(assert.fail); -server.listen(1, '1.1.1.1', assert.fail); -server.on('error', common.mustCall(function(e) { - assert.equal(e.address, '1.1.1.1'); - assert.equal(e.port, 1); - assert.equal(e.syscall, 'listen'); -})); diff --git a/test/simple/test-net-better-error-messages-path.js b/test/simple/test-net-better-error-messages-path.js deleted file mode 100644 index dea4a1045..000000000 --- a/test/simple/test-net-better-error-messages-path.js +++ /dev/null @@ -1,12 +0,0 @@ -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); -var fp = '/tmp/fadagagsdfgsdf'; -var c = net.connect(fp); - -c.on('connect', assert.fail); - -c.on('error', common.mustCall(function(e) { - assert.equal(e.code, 'ENOENT'); - assert.equal(e.message, 'connect ENOENT ' + fp); -})); diff --git a/test/simple/test-net-better-error-messages-port-hostname.js b/test/simple/test-net-better-error-messages-port-hostname.js deleted file mode 100644 index 3817dbb92..000000000 --- a/test/simple/test-net-better-error-messages-port-hostname.js +++ /dev/null @@ -1,13 +0,0 @@ -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - -var c = net.createConnection(common.PORT, 'blah.blah'); - -c.on('connect', assert.fail); - -c.on('error', common.mustCall(function(e) { - assert.equal(e.code, 'ENOTFOUND'); - assert.equal(e.port, common.PORT); - assert.equal(e.hostname, 'blah.blah'); -})); diff --git a/test/simple/test-net-better-error-messages-port.js b/test/simple/test-net-better-error-messages-port.js deleted file mode 100644 index a8c16a703..000000000 --- a/test/simple/test-net-better-error-messages-port.js +++ /dev/null @@ -1,13 +0,0 @@ -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - -var c = net.createConnection(common.PORT); - -c.on('connect', assert.fail); - -c.on('error', common.mustCall(function(e) { - assert.equal(e.code, 'ECONNREFUSED'); - assert.equal(e.port, common.PORT); - assert.equal(e.address, '127.0.0.1'); -})); diff --git a/test/simple/test-net-binary.js b/test/simple/test-net-binary.js deleted file mode 100644 index 310046584..000000000 --- a/test/simple/test-net-binary.js +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var binaryString = ''; -for (var i = 255; i >= 0; i--) { - var s = '\'\\' + i.toString(8) + '\''; - var S = eval(s); - common.error(s + - ' ' + - JSON.stringify(S) + - ' ' + - JSON.stringify(String.fromCharCode(i)) + - ' ' + - S.charCodeAt(0)); - assert.ok(S.charCodeAt(0) == i); - assert.ok(S == String.fromCharCode(i)); - binaryString += S; -} - -// safe constructor -var echoServer = net.Server(function(connection) { - console.error('SERVER got connection'); - connection.setEncoding('binary'); - connection.on('data', function(chunk) { - common.error('SERVER recved: ' + JSON.stringify(chunk)); - connection.write(chunk, 'binary'); - }); - connection.on('end', function() { - console.error('SERVER ending'); - connection.end(); - }); -}); -echoServer.listen(common.PORT); - -var recv = ''; - -echoServer.on('listening', function() { - console.error('SERVER listening'); - var j = 0; - var c = net.createConnection({ - port: common.PORT - }); - - c.setEncoding('binary'); - c.on('data', function(chunk) { - console.error('CLIENT data %j', chunk); - var n = j + chunk.length; - while (j < n && j < 256) { - common.error('CLIENT write ' + j); - c.write(String.fromCharCode(j), 'binary'); - j++; - } - if (j === 256) { - console.error('CLIENT ending'); - c.end(); - } - recv += chunk; - }); - - c.on('connect', function() { - console.error('CLIENT connected, writing'); - c.write(binaryString, 'binary'); - }); - - c.on('close', function() { - console.error('CLIENT closed'); - console.dir(recv); - echoServer.close(); - }); - - c.on('finish', function() { - console.error('CLIENT finished'); - }); -}); - -process.on('exit', function() { - console.log('recv: ' + JSON.stringify(recv)); - - assert.equal(2 * 256, recv.length); - - var a = recv.split(''); - - var first = a.slice(0, 256).reverse().join(''); - console.log('first: ' + JSON.stringify(first)); - - var second = a.slice(256, 2 * 256).join(''); - console.log('second: ' + JSON.stringify(second)); - - assert.equal(first, second); -}); diff --git a/test/simple/test-net-bind-twice.js b/test/simple/test-net-bind-twice.js deleted file mode 100644 index 58086cc96..000000000 --- a/test/simple/test-net-bind-twice.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var gotError = false; - -process.on('exit', function() { - assert(gotError); -}); - -function dontCall() { - assert(false); -} - -var server1 = net.createServer(dontCall); -server1.listen(common.PORT, '127.0.0.1', function() {}); - -var server2 = net.createServer(dontCall); -server2.listen(common.PORT, '127.0.0.1', dontCall); - -server2.on('error', function(e) { - assert.equal(e.code, 'EADDRINUSE'); - server1.close(); - gotError = true; -}); diff --git a/test/simple/test-net-buffersize.js b/test/simple/test-net-buffersize.js deleted file mode 100644 index 5759503a1..000000000 --- a/test/simple/test-net-buffersize.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var iter = 10; - -var server = net.createServer(function(socket) { - socket.on('readable', function() { - socket.read(); - }); - - socket.on('end', function() { - server.close(); - }); -}); - -server.listen(common.PORT, function() { - var client = net.connect(common.PORT); - - client.on('finish', function() { - assert.strictEqual(client.bufferSize, 0); - }); - - for (var i = 1; i < iter; i++) { - client.write('a'); - assert.strictEqual(client.bufferSize, i); - } - - client.end(); -}); diff --git a/test/simple/test-net-bytes-stats.js b/test/simple/test-net-bytes-stats.js deleted file mode 100644 index 0cb08009e..000000000 --- a/test/simple/test-net-bytes-stats.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var tcpPort = common.PORT; -var bytesRead = 0; -var bytesWritten = 0; -var count = 0; - -var tcp = net.Server(function(s) { - console.log('tcp server connection'); - - // trigger old mode. - s.resume(); - - s.on('end', function() { - bytesRead += s.bytesRead; - console.log('tcp socket disconnect #' + count); - }); -}); - -tcp.listen(common.PORT, function doTest() { - console.error('listening'); - var socket = net.createConnection(tcpPort); - - socket.on('connect', function() { - count++; - console.error('CLIENT connect #%d', count); - - socket.write('foo', function() { - console.error('CLIENT: write cb'); - socket.end('bar'); - }); - }); - - socket.on('finish', function() { - bytesWritten += socket.bytesWritten; - console.error('CLIENT end event #%d', count); - }); - - socket.on('close', function() { - console.error('CLIENT close event #%d', count); - console.log('Bytes read: ' + bytesRead); - console.log('Bytes written: ' + bytesWritten); - if (count < 2) { - console.error('RECONNECTING'); - socket.connect(tcpPort); - } else { - tcp.close(); - } - }); -}); - -process.on('exit', function() { - assert.equal(bytesRead, 12); - assert.equal(bytesWritten, 12); -}); diff --git a/test/simple/test-net-can-reset-timeout.js b/test/simple/test-net-can-reset-timeout.js deleted file mode 100644 index b9ea97efe..000000000 --- a/test/simple/test-net-can-reset-timeout.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var net = require('net'); -var common = require('../common'); -var assert = require('assert'); - -var timeoutCount = 0; - -var server = net.createServer(function(stream) { - stream.setTimeout(100); - - stream.resume(); - - stream.on('timeout', function() { - console.log('timeout'); - // try to reset the timeout. - stream.write('WHAT.'); - // don't worry, the socket didn't *really* time out, we're just thinking - // it did. - timeoutCount += 1; - }); - - stream.on('end', function() { - console.log('server side end'); - stream.end(); - }); -}); - -server.listen(common.PORT, function() { - var c = net.createConnection(common.PORT); - - c.on('data', function() { - c.end(); - }); - - c.on('end', function() { - console.log('client side end'); - server.close(); - }); -}); - - -process.on('exit', function() { - assert.equal(1, timeoutCount); -}); diff --git a/test/simple/test-net-connect-buffer.js b/test/simple/test-net-connect-buffer.js deleted file mode 100644 index 679e18e90..000000000 --- a/test/simple/test-net-connect-buffer.js +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var tcpPort = common.PORT; -var dataWritten = false; -var connectHappened = false; - -var tcp = net.Server(function(s) { - tcp.close(); - - console.log('tcp server connection'); - - var buf = ''; - s.on('data', function(d) { - buf += d; - }); - - s.on('end', function() { - console.error('SERVER: end', buf.toString()); - assert.equal(buf, "L'État, c'est moi"); - console.log('tcp socket disconnect'); - s.end(); - }); - - s.on('error', function(e) { - console.log('tcp server-side error: ' + e.message); - process.exit(1); - }); -}); - -tcp.listen(common.PORT, function() { - var socket = net.Stream({ highWaterMark: 0 }); - - console.log('Connecting to socket '); - - socket.connect(tcpPort, function() { - console.log('socket connected'); - connectHappened = true; - }); - - console.log('_connecting = ' + socket._connecting); - - assert.equal('opening', socket.readyState); - - // Make sure that anything besides a buffer or a string throws. - [null, - true, - false, - undefined, - 1, - 1.0, - 1 / 0, - +Infinity, - -Infinity, - [], - {} - ].forEach(function(v) { - function f() { - console.error('write', v); - socket.write(v); - } - assert.throws(f, TypeError); - }); - - // Write a string that contains a multi-byte character sequence to test that - // `bytesWritten` is incremented with the # of bytes, not # of characters. - var a = "L'État, c'est "; - var b = 'moi'; - - // We're still connecting at this point so the datagram is first pushed onto - // the connect queue. Make sure that it's not added to `bytesWritten` again - // when the actual write happens. - var r = socket.write(a, function(er) { - console.error('write cb'); - dataWritten = true; - assert.ok(connectHappened); - console.error('socket.bytesWritten', socket.bytesWritten); - //assert.equal(socket.bytesWritten, Buffer(a + b).length); - console.error('data written'); - }); - console.error('socket.bytesWritten', socket.bytesWritten); - console.error('write returned', r); - - assert.equal(socket.bytesWritten, Buffer(a).length); - - assert.equal(false, r); - socket.end(b); - - assert.equal('opening', socket.readyState); -}); - -process.on('exit', function() { - assert.ok(connectHappened); - assert.ok(dataWritten); -}); diff --git a/test/simple/test-net-connect-handle-econnrefused.js b/test/simple/test-net-connect-handle-econnrefused.js deleted file mode 100644 index e890b6a8d..000000000 --- a/test/simple/test-net-connect-handle-econnrefused.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - - -// Hopefully nothing is running on common.PORT -var c = net.createConnection(common.PORT); - -c.on('connect', function() { - console.error('connected?!'); - assert.ok(false); -}); - -var gotError = false; -c.on('error', function(e) { - console.error('couldn\'t connect.'); - gotError = true; - assert.equal('ECONNREFUSED', e.code); -}); - - -process.on('exit', function() { - assert.ok(gotError); -}); diff --git a/test/simple/test-net-connect-immediate-finish.js b/test/simple/test-net-connect-immediate-finish.js deleted file mode 100644 index ac2a61331..000000000 --- a/test/simple/test-net-connect-immediate-finish.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var gotError = false; - -var client = net.connect({ - host: 'no.way.you.will.resolve.this', - port: common.PORT -}); - -client.once('error', function(err) { - gotError = true; -}); - -client.end(); - -process.on('exit', function() { - assert(gotError); -}); diff --git a/test/simple/test-net-connect-options-ipv6.js b/test/simple/test-net-connect-options-ipv6.js deleted file mode 100644 index 9dd60c1cb..000000000 --- a/test/simple/test-net-connect-options-ipv6.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var dns = require('dns'); - -if (!common.hasIPv6) { - console.error('Skipping test, no IPv6 support'); - return; -} - -var serverGotEnd = false; -var clientGotEnd = false; - -dns.lookup('localhost', 6, function(err) { - if (err) { - console.error('Looks like IPv6 is not really supported'); - console.error(err); - return; - } - - var server = net.createServer({allowHalfOpen: true}, function(socket) { - socket.resume(); - socket.on('end', function() { - serverGotEnd = true; - }); - socket.end(); - }); - - server.listen(common.PORT, '::1', function() { - var client = net.connect({ - host: 'localhost', - port: common.PORT, - family: 6, - allowHalfOpen: true - }, function() { - console.error('client connect cb'); - client.resume(); - client.on('end', function() { - clientGotEnd = true; - setTimeout(function() { - assert(client.writable); - client.end(); - }, 10); - }); - client.on('close', function() { - server.close(); - }); - }); - }); - - process.on('exit', function() { - console.error('exit', serverGotEnd, clientGotEnd); - assert(serverGotEnd); - assert(clientGotEnd); - }); -}); diff --git a/test/simple/test-net-connect-options.js b/test/simple/test-net-connect-options.js deleted file mode 100644 index 6be3696da..000000000 --- a/test/simple/test-net-connect-options.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var serverGotEnd = false; -var clientGotEnd = false; - -var server = net.createServer({allowHalfOpen: true}, function(socket) { - socket.resume(); - socket.on('end', function() { - serverGotEnd = true; - }); - socket.end(); -}); - -server.listen(common.PORT, function() { - var client = net.connect({ - host: '127.0.0.1', - port: common.PORT, - allowHalfOpen: true - }, function() { - console.error('client connect cb'); - client.resume(); - client.on('end', function() { - clientGotEnd = true; - setTimeout(function() { - assert(client.writable); - client.end(); - }, 10); - }); - client.on('close', function() { - server.close(); - }); - }); -}); - -process.on('exit', function() { - console.error('exit', serverGotEnd, clientGotEnd); - assert(serverGotEnd); - assert(clientGotEnd); -}); diff --git a/test/simple/test-net-connect-paused-connection.js b/test/simple/test-net-connect-paused-connection.js deleted file mode 100644 index c38f51e36..000000000 --- a/test/simple/test-net-connect-paused-connection.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. - -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: - -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); - -var net = require('net'); - -net.createServer(function(conn) { - conn.unref(); -}).listen(8124).unref(); - -net.connect(8124, 'localhost').pause(); - -setTimeout(function() { - assert.fail('expected to exit'); -}, 1000).unref(); diff --git a/test/simple/test-net-create-connection.js b/test/simple/test-net-create-connection.js deleted file mode 100644 index 12f7f0be6..000000000 --- a/test/simple/test-net-create-connection.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var tcpPort = common.PORT; -var clientConnected = 0; -var serverConnected = 0; - -var server = net.createServer(function(socket) { - socket.end(); - if (++serverConnected === 4) { - server.close(); - } -}); -server.listen(tcpPort, 'localhost', function() { - function cb() { - ++clientConnected; - } - - net.createConnection(tcpPort).on('connect', cb); - net.createConnection(tcpPort, 'localhost').on('connect', cb); - net.createConnection(tcpPort, cb); - net.createConnection(tcpPort, 'localhost', cb); - - assert.throws(function () { - net.createConnection({ - port: 'invalid!' - }, cb); - }); -}); - -process.on('exit', function() { - assert.equal(clientConnected, 4); -}); - diff --git a/test/simple/test-net-dns-error.js b/test/simple/test-net-dns-error.js deleted file mode 100644 index f7221389a..000000000 --- a/test/simple/test-net-dns-error.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -var expected_bad_connections = 1; -var actual_bad_connections = 0; - -var host = '********'; -host += host; -host += host; -host += host; -host += host; -host += host; - -function do_not_call() { - throw new Error('This function should not have been called.'); -} - -var socket = net.connect(42, host, do_not_call); -socket.on('error', function(err) { - assert.equal(err.code, 'ENOTFOUND'); - actual_bad_connections++; -}); -socket.on('lookup', function(err, ip, type) { - assert(err instanceof Error); - assert.equal(err.code, 'ENOTFOUND'); - assert.equal(ip, undefined); - assert.equal(type, undefined); -}); - -process.on('exit', function() { - assert.equal(actual_bad_connections, expected_bad_connections); -}); diff --git a/test/simple/test-net-dns-lookup.js b/test/simple/test-net-dns-lookup.js deleted file mode 100644 index 5628e4d8a..000000000 --- a/test/simple/test-net-dns-lookup.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var ok = false; - -var server = net.createServer(function(client) { - client.end(); - server.close(); -}); - -server.listen(common.PORT, '127.0.0.1', function() { - net.connect(common.PORT, '127.0.0.1').on('lookup', function(err, ip, type) { - assert.equal(err, null); - assert.equal(ip, '127.0.0.1'); - assert.equal(type, '4'); - ok = true; - }); -}); - -process.on('exit', function() { - assert(ok); -}); diff --git a/test/simple/test-net-during-close.js b/test/simple/test-net-during-close.js deleted file mode 100644 index 489d77479..000000000 --- a/test/simple/test-net-during-close.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var accessedProperties = false; - -var server = net.createServer(function(socket) { - socket.end(); -}); - -server.listen(common.PORT, function() { - var client = net.createConnection(common.PORT); - server.close(); - // server connection event has not yet fired - // client is still attempting to connect - assert.doesNotThrow(function() { - client.remoteAddress; - client.remoteFamily; - client.remotePort; - }); - accessedProperties = true; - // exit now, do not wait for the client error event - process.exit(0); -}); - -process.on('exit', function() { - assert(accessedProperties); -}); diff --git a/test/simple/test-net-eaddrinuse.js b/test/simple/test-net-eaddrinuse.js deleted file mode 100644 index 2192ea224..000000000 --- a/test/simple/test-net-eaddrinuse.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var server1 = net.createServer(function(socket) { -}); -var server2 = net.createServer(function(socket) { -}); -server1.listen(common.PORT); -server2.on('error', function(error) { - assert.equal(true, error.message.indexOf('EADDRINUSE') >= 0); - server1.close(); -}); -server2.listen(common.PORT); diff --git a/test/simple/test-net-end-without-connect.js b/test/simple/test-net-end-without-connect.js deleted file mode 100644 index 156071a0d..000000000 --- a/test/simple/test-net-end-without-connect.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var net = require('net'); - -var sock = new net.Socket; -sock.end(); // Should not throw. diff --git a/test/simple/test-net-error-twice.js b/test/simple/test-net-error-twice.js deleted file mode 100644 index 955eea6c0..000000000 --- a/test/simple/test-net-error-twice.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var buf = new Buffer(10 * 1024 * 1024); - -buf.fill(0x62); - -var errs = []; - -var srv = net.createServer(function onConnection(conn) { - conn.write(buf); - conn.on('error', function (err) { - errs.push(err); - if (errs.length > 1 && errs[0] === errs[1]) - assert(false, "We should not be emitting the same error twice"); - }); - conn.on('close', function() { - srv.unref(); - }); -}).listen(common.PORT, function () { - var client = net.connect({ port: common.PORT }); - - client.on('connect', function () { - client.destroy(); - }); -}); - -process.on('exit', function() { - console.log(errs); - assert.equal(errs.length, 1); -}); diff --git a/test/simple/test-net-isip.js b/test/simple/test-net-isip.js deleted file mode 100644 index 0d324007f..000000000 --- a/test/simple/test-net-isip.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -assert.equal(net.isIP('127.0.0.1'), 4); -assert.equal(net.isIP('x127.0.0.1'), 0); -assert.equal(net.isIP('example.com'), 0); -assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000'), 6); -assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:0000:0000::0000'), 0); -assert.equal(net.isIP('1050:0:0:0:5:600:300c:326b'), 6); -assert.equal(net.isIP('2001:252:0:1::2008:6'), 6); -assert.equal(net.isIP('2001:dead:beef:1::2008:6'), 6); -assert.equal(net.isIP('2001::'), 6); -assert.equal(net.isIP('2001:dead::'), 6); -assert.equal(net.isIP('2001:dead:beef::'), 6); -assert.equal(net.isIP('2001:dead:beef:1::'), 6); -assert.equal(net.isIP('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'), 6); -assert.equal(net.isIP(':2001:252:0:1::2008:6:'), 0); -assert.equal(net.isIP(':2001:252:0:1::2008:6'), 0); -assert.equal(net.isIP('2001:252:0:1::2008:6:'), 0); -assert.equal(net.isIP('2001:252::1::2008:6'), 0); -assert.equal(net.isIP('::2001:252:1:2008:6'), 6); -assert.equal(net.isIP('::2001:252:1:1.1.1.1'), 6); -assert.equal(net.isIP('::2001:252:1:255.255.255.255'), 6); -assert.equal(net.isIP('::2001:252:1:255.255.255.255.76'), 0); -assert.equal(net.isIP('::anything'), 0); -assert.equal(net.isIP('::1'), 6); -assert.equal(net.isIP('::'), 6); -assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); -assert.equal(net.isIP('0'), 0); -assert.equal(net.isIP(), 0); -assert.equal(net.isIP(""), 0); - -assert.equal(net.isIPv4('127.0.0.1'), true); -assert.equal(net.isIPv4('example.com'), false); -assert.equal(net.isIPv4('2001:252:0:1::2008:6'), false); - -assert.equal(net.isIPv6('127.0.0.1'), false); -assert.equal(net.isIPv6('example.com'), false); -assert.equal(net.isIPv6('2001:252:0:1::2008:6'), true); diff --git a/test/simple/test-net-keepalive.js b/test/simple/test-net-keepalive.js deleted file mode 100644 index b09d9d5d6..000000000 --- a/test/simple/test-net-keepalive.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var serverConnection; -var echoServer = net.createServer(function(connection) { - serverConnection = connection; - connection.setTimeout(0); - assert.notEqual(connection.setKeepAlive, undefined); - // send a keepalive packet after 1000 ms - connection.setKeepAlive(true, 1000); - connection.on('end', function() { - connection.end(); - }); -}); -echoServer.listen(common.PORT); - -echoServer.on('listening', function() { - var clientConnection = net.createConnection(common.PORT); - clientConnection.setTimeout(0); - - setTimeout(function() { - // make sure both connections are still open - assert.equal(serverConnection.readyState, 'open'); - assert.equal(clientConnection.readyState, 'open'); - serverConnection.end(); - clientConnection.end(); - echoServer.close(); - }, 1200); -}); diff --git a/test/simple/test-net-large-string.js b/test/simple/test-net-large-string.js deleted file mode 100644 index 877dc7c78..000000000 --- a/test/simple/test-net-large-string.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var kPoolSize = 40 * 1024; -var data = ''; -for (var i = 0; i < kPoolSize; ++i) { - data += 'あ'; // 3bytes -} -var receivedSize = 0; -var encoding = 'UTF-8'; - -var server = net.createServer(function(socket) { - socket.setEncoding(encoding); - socket.on('data', function(data) { - receivedSize += data.length; - }); - socket.on('end', function() { - socket.end(); - }); -}); - -server.listen(common.PORT, function() { - var client = net.createConnection(common.PORT); - client.on('end', function() { - server.close(); - }); - client.write(data, encoding); - client.end(); -}); - -process.on('exit', function() { - assert.equal(receivedSize, kPoolSize); -}); diff --git a/test/simple/test-net-listen-close-server.js b/test/simple/test-net-listen-close-server.js deleted file mode 100644 index 4a3233a8f..000000000 --- a/test/simple/test-net-listen-close-server.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var gotError = false; - -var server = net.createServer(function(socket) { -}); -server.listen(common.PORT, function() { - assert(false); -}); -server.on('error', function(error) { - common.debug(error); - assert(false); -}); -server.close(); diff --git a/test/simple/test-net-listen-error.js b/test/simple/test-net-listen-error.js deleted file mode 100644 index 17ec762ca..000000000 --- a/test/simple/test-net-listen-error.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var gotError = false; - -var server = net.createServer(function(socket) { -}); -server.listen(1, '1.1.1.1', function() { // EACCESS or EADDRNOTAVAIL - assert(false); -}); -server.on('error', function(error) { - common.debug(error); - gotError = true; -}); - -process.on('exit', function() { - assert(gotError); -}); diff --git a/test/simple/test-net-listen-exclusive-random-ports.js b/test/simple/test-net-listen-exclusive-random-ports.js deleted file mode 100644 index 2c0aa4904..000000000 --- a/test/simple/test-net-listen-exclusive-random-ports.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -function noop() {} - -if (cluster.isMaster) { - var worker1 = cluster.fork(); - - worker1.on('message', function(port1) { - assert.equal(port1, port1 | 0, 'first worker could not listen'); - var worker2 = cluster.fork(); - - worker2.on('message', function(port2) { - assert.equal(port2, port2 | 0, 'second worker could not listen'); - assert.notEqual(port1, port2, 'ports should not be equal'); - worker1.kill(); - worker2.kill(); - }); - }); -} else { - var server = net.createServer(noop); - - server.on('error', function(err) { - process.send(err.code); - }); - - server.listen({ - port: 0, - exclusive: true - }, function() { - process.send(server.address().port); - }); -} diff --git a/test/simple/test-net-listen-fd0.js b/test/simple/test-net-listen-fd0.js deleted file mode 100644 index ac5896ee8..000000000 --- a/test/simple/test-net-listen-fd0.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var gotError = false; - -process.on('exit', function() { - assert(gotError instanceof Error); -}); - -// this should fail with an async EINVAL error, not throw an exception -net.createServer(assert.fail).listen({fd:0}).on('error', function(e) { - switch(e.code) { - case 'EINVAL': - case 'ENOTSOCK': - gotError = e; - break - } -}); diff --git a/test/simple/test-net-listen-shared-ports.js b/test/simple/test-net-listen-shared-ports.js deleted file mode 100644 index 7422e491f..000000000 --- a/test/simple/test-net-listen-shared-ports.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var net = require('net'); - -function noop() {} - -if (cluster.isMaster) { - var worker1 = cluster.fork(); - - worker1.on('message', function(msg) { - assert.equal(msg, 'success'); - var worker2 = cluster.fork(); - - worker2.on('message', function(msg) { - assert.equal(msg, 'server2:EADDRINUSE'); - worker1.kill(); - worker2.kill(); - }); - }); -} else { - var server1 = net.createServer(noop); - var server2 = net.createServer(noop); - - server1.on('error', function(err) { - // no errors expected - process.send('server1:' + err.code); - }); - - server2.on('error', function(err) { - // an error is expected on the second worker - process.send('server2:' + err.code); - }); - - server1.listen({ - host: 'localhost', - port: common.PORT, - exclusive: false - }, function() { - server2.listen({port: common.PORT + 1, exclusive: true}, function() { - // the first worker should succeed - process.send('success'); - }); - }); -} diff --git a/test/simple/test-net-local-address-port.js b/test/simple/test-net-local-address-port.js deleted file mode 100644 index 0f59cec9b..000000000 --- a/test/simple/test-net-local-address-port.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var conns = 0, conns_closed = 0; - -var server = net.createServer(function(socket) { - conns++; - assert.equal('127.0.0.1', socket.localAddress); - assert.equal(socket.localPort, common.PORT); - socket.on('end', function() { - server.close(); - }); - socket.resume(); -}); - -server.listen(common.PORT, '127.0.0.1', function() { - var client = net.createConnection(common.PORT, '127.0.0.1'); - client.on('connect', function() { - client.end(); - }); -}); - -process.on('exit', function() { - assert.equal(1, conns); -}); diff --git a/test/simple/test-net-localerror.js b/test/simple/test-net-localerror.js deleted file mode 100644 index c4d04aa92..000000000 --- a/test/simple/test-net-localerror.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var server = net.createServer(function(socket) { - assert.ok(false, 'no clients should connect'); -}).listen(common.PORT).on('listening', function() { - server.unref(); - - function test1(next) { - connect({ - host: '127.0.0.1', - port: common.PORT, - localPort: 'foobar', - }, - 'localPort should be a number: foobar', - next); - } - - function test2(next) { - connect({ - host: '127.0.0.1', - port: common.PORT, - localAddress: 'foobar', - }, - 'localAddress should be a valid IP: foobar', - next) - } - - test1(test2); -}) - -function connect(opts, msg, cb) { - var client = net.connect(opts).on('connect', function() { - assert.ok(false, 'we should never connect'); - }).on('error', function(err) { - assert.strictEqual(err.message, msg); - if (cb) cb(); - }); -} diff --git a/test/simple/test-net-localport.js b/test/simple/test-net-localport.js deleted file mode 100644 index 34fa377dc..000000000 --- a/test/simple/test-net-localport.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var server = net.createServer(function(socket) { - console.log(socket.remotePort); - assert.strictEqual(socket.remotePort, common.PORT + 1); - socket.end(); - socket.on('close', function() { - server.close(); - }); -}).listen(common.PORT).on('listening', function() { - var client = net.connect({ - host: '127.0.0.1', - port: common.PORT, - localPort: common.PORT + 1, - }).on('connect', function() { - assert.strictEqual(client.localPort, common.PORT + 1); - }); -}) diff --git a/test/simple/test-net-pause-resume-connecting.js b/test/simple/test-net-pause-resume-connecting.js deleted file mode 100644 index 264dc9680..000000000 --- a/test/simple/test-net-pause-resume-connecting.js +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - net = require('net'); - -var connections = 0, - dataEvents = 0, - conn; - - -// Server -var server = net.createServer(function(conn) { - connections++; - conn.end('This was the year he fell to pieces.'); - - if (connections === 5) - server.close(); -}); - -server.listen(common.PORT); - - -// Client 1 -conn = require('net').createConnection(common.PORT, 'localhost'); -conn.resume(); -conn.on('data', onDataOk); - - -// Client 2 -conn = require('net').createConnection(common.PORT, 'localhost'); -conn.pause(); -conn.resume(); -conn.on('data', onDataOk); - - -// Client 3 -conn = require('net').createConnection(common.PORT, 'localhost'); -conn.pause(); -conn.on('data', onDataError); -scheduleTearDown(conn); - - -// Client 4 -conn = require('net').createConnection(common.PORT, 'localhost'); -conn.resume(); -conn.pause(); -conn.resume(); -conn.on('data', onDataOk); - - -// Client 5 -conn = require('net').createConnection(common.PORT, 'localhost'); -conn.resume(); -conn.resume(); -conn.pause(); -conn.on('data', onDataError); -scheduleTearDown(conn); - - -// Client helper functions -function onDataError() { - assert(false); -} - -function onDataOk() { - dataEvents++; -} - -function scheduleTearDown(conn) { - setTimeout(function() { - conn.removeAllListeners('data'); - conn.resume(); - }, 100); -} - - -// Exit sanity checks -process.on('exit', function() { - assert.strictEqual(connections, 5); - assert.strictEqual(dataEvents, 3); -}); diff --git a/test/simple/test-net-pingpong.js b/test/simple/test-net-pingpong.js deleted file mode 100644 index ff7c97a03..000000000 --- a/test/simple/test-net-pingpong.js +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -var tests_run = 0; - -function pingPongTest(port, host) { - var N = 1000; - var count = 0; - var sentPongs = 0; - var sent_final_ping = false; - - var server = net.createServer({ allowHalfOpen: true }, function(socket) { - console.log('connection: ' + socket.remoteAddress); - assert.equal(server, socket.server); - assert.equal(1, server.connections); - - socket.setNoDelay(); - socket.timeout = 0; - - socket.setEncoding('utf8'); - socket.on('data', function(data) { - // Since we never queue data (we're always waiting for the PING - // before sending a pong) the writeQueueSize should always be less - // than one message. - assert.ok(0 <= socket.bufferSize && socket.bufferSize <= 4); - - console.log('server got: ' + data); - assert.equal(true, socket.writable); - assert.equal(true, socket.readable); - assert.equal(true, count <= N); - if (/PING/.exec(data)) { - socket.write('PONG', function() { - sentPongs++; - console.error('sent PONG'); - }); - } - }); - - socket.on('end', function() { - console.error(socket); - assert.equal(true, socket.allowHalfOpen); - assert.equal(true, socket.writable); // because allowHalfOpen - assert.equal(false, socket.readable); - socket.end(); - }); - - socket.on('error', function(e) { - throw e; - }); - - socket.on('close', function() { - console.log('server socket.endd'); - assert.equal(false, socket.writable); - assert.equal(false, socket.readable); - socket.server.close(); - }); - }); - - - server.listen(port, host, function() { - console.log('server listening on ' + port + ' ' + host); - - var client = net.createConnection(port, host); - - client.setEncoding('ascii'); - client.on('connect', function() { - assert.equal(true, client.readable); - assert.equal(true, client.writable); - client.write('PING'); - }); - - client.on('data', function(data) { - console.log('client got: ' + data); - - assert.equal('PONG', data); - count += 1; - - if (sent_final_ping) { - assert.equal(false, client.writable); - assert.equal(true, client.readable); - return; - } else { - assert.equal(true, client.writable); - assert.equal(true, client.readable); - } - - if (count < N) { - client.write('PING'); - } else { - sent_final_ping = true; - client.write('PING'); - client.end(); - } - }); - - client.on('close', function() { - console.log('client.end'); - assert.equal(N + 1, count); - assert.equal(N + 1, sentPongs); - assert.equal(true, sent_final_ping); - tests_run += 1; - }); - - client.on('error', function(e) { - throw e; - }); - }); -} - -/* All are run at once, so run on different ports */ -console.log(common.PIPE); -pingPongTest(common.PIPE); -pingPongTest(common.PORT); -pingPongTest(common.PORT + 1, 'localhost'); -if (common.hasIPv6) - pingPongTest(common.PORT + 2, '::1'); - -process.on('exit', function() { - if (common.hasIPv6) - assert.equal(4, tests_run); - else - assert.equal(3, tests_run); - console.log('done'); -}); diff --git a/test/simple/test-net-pipe-connect-errors.js b/test/simple/test-net-pipe-connect-errors.js deleted file mode 100644 index 07dd4fe4a..000000000 --- a/test/simple/test-net-pipe-connect-errors.js +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var fs = require('fs'); -var net = require('net'); -var path = require('path'); -var assert = require('assert'); -var common = require('../common'); - -var notSocketErrorFired = false; -var noEntErrorFired = false; -var accessErrorFired = false; - -// Test if ENOTSOCK is fired when trying to connect to a file which is not -// a socket. - -var emptyTxt; - -if (process.platform === 'win32') { - // on Win, common.PIPE will be a named pipe, so we use an existing empty - // file instead - emptyTxt = path.join(common.fixturesDir, 'empty.txt'); -} else { - // use common.PIPE to ensure we stay within POSIX socket path length - // restrictions, even on CI - emptyTxt = common.PIPE + '.txt'; - - function cleanup() { - try { - fs.unlinkSync(emptyTxt); - } catch (e) { - if (e.code != 'ENOENT') - throw e; - } - } - process.on('exit', cleanup); - cleanup(); - fs.writeFileSync(emptyTxt, ''); -} - -var notSocketClient = net.createConnection(emptyTxt, function() { - assert.ok(false); -}); - -notSocketClient.on('error', function(err) { - assert(err.code === 'ENOTSOCK' || err.code === 'ECONNREFUSED'); - notSocketErrorFired = true; -}); - - -// Trying to connect to not-existing socket should result in ENOENT error -var noEntSocketClient = net.createConnection('no-ent-file', function() { - assert.ok(false); -}); - -noEntSocketClient.on('error', function(err) { - assert.equal(err.code, 'ENOENT'); - noEntErrorFired = true; -}); - - -// On Windows or when running as root, a chmod has no effect on named pipes -if (process.platform !== 'win32' && process.getuid() !== 0) { - // Trying to connect to a socket one has no access to should result in EACCES - var accessServer = net.createServer(function() { - assert.ok(false); - }); - accessServer.listen(common.PIPE, function() { - fs.chmodSync(common.PIPE, 0); - - var accessClient = net.createConnection(common.PIPE, function() { - assert.ok(false); - }); - - accessClient.on('error', function(err) { - assert.equal(err.code, 'EACCES'); - accessErrorFired = true; - accessServer.close(); - }); - }); -} - - -// Assert that all error events were fired -process.on('exit', function() { - assert.ok(notSocketErrorFired); - assert.ok(noEntErrorFired); - if (process.platform !== 'win32' && process.getuid() !== 0) { - assert.ok(accessErrorFired); - } -}); - diff --git a/test/simple/test-net-reconnect-error.js b/test/simple/test-net-reconnect-error.js deleted file mode 100644 index 6094e943c..000000000 --- a/test/simple/test-net-reconnect-error.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); -var N = 50; -var client_error_count = 0; -var disconnect_count = 0; - -// Hopefully nothing is running on common.PORT -var c = net.createConnection(common.PORT); - -c.on('connect', function() { - console.error('CLIENT connected'); - assert.ok(false); -}); - -c.on('error', function(e) { - console.error('CLIENT error: ' + e.code); - client_error_count++; - assert.equal('ECONNREFUSED', e.code); -}); - -c.on('close', function() { - console.log('CLIENT disconnect'); - if (disconnect_count++ < N) - c.connect(common.PORT); // reconnect -}); - -process.on('exit', function() { - assert.equal(N + 1, disconnect_count); - assert.equal(N + 1, client_error_count); -}); diff --git a/test/simple/test-net-reconnect.js b/test/simple/test-net-reconnect.js deleted file mode 100644 index ffc2a73c6..000000000 --- a/test/simple/test-net-reconnect.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -var N = 50; -var c = 0; -var client_recv_count = 0; -var client_end_count = 0; -var disconnect_count = 0; - -var server = net.createServer(function(socket) { - console.error('SERVER: got socket connection'); - socket.resume(); - - console.error('SERVER connect, writing'); - socket.write('hello\r\n'); - - socket.on('end', function() { - console.error('SERVER socket end, calling end()'); - socket.end(); - }); - - socket.on('close', function(had_error) { - console.log('SERVER had_error: ' + JSON.stringify(had_error)); - assert.equal(false, had_error); - }); -}); - -server.listen(common.PORT, function() { - console.log('SERVER listening'); - var client = net.createConnection(common.PORT); - - client.setEncoding('UTF8'); - - client.on('connect', function() { - console.error('CLIENT connected', client._writableState); - }); - - client.on('data', function(chunk) { - client_recv_count += 1; - console.log('client_recv_count ' + client_recv_count); - assert.equal('hello\r\n', chunk); - console.error('CLIENT: calling end', client._writableState); - client.end(); - }); - - client.on('end', function() { - console.error('CLIENT end'); - client_end_count++; - }); - - client.on('close', function(had_error) { - console.log('CLIENT disconnect'); - assert.equal(false, had_error); - if (disconnect_count++ < N) - client.connect(common.PORT); // reconnect - else - server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(N + 1, disconnect_count); - assert.equal(N + 1, client_recv_count); - assert.equal(N + 1, client_end_count); -}); - diff --git a/test/simple/test-net-remote-address-port.js b/test/simple/test-net-remote-address-port.js deleted file mode 100644 index 0cfe47afe..000000000 --- a/test/simple/test-net-remote-address-port.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -var conns = 0, conns_closed = 0; - -var remoteAddrCandidates = [ '127.0.0.1']; -if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1'); - -var remoteFamilyCandidates = ['IPv4']; -if (common.hasIPv6) remoteFamilyCandidates.push('IPv6'); - -var server = net.createServer(function(socket) { - conns++; - assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); - assert.ok(socket.remotePort); - assert.notEqual(socket.remotePort, common.PORT); - socket.on('end', function() { - if (++conns_closed == 2) server.close(); - }); - socket.resume(); -}); - -server.listen(common.PORT, 'localhost', function() { - var client = net.createConnection(common.PORT, 'localhost'); - var client2 = net.createConnection(common.PORT); - client.on('connect', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(client.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(client.remoteFamily)); - assert.equal(common.PORT, client.remotePort); - client.end(); - }); - client2.on('connect', function() { - assert.notEqual(-1, remoteAddrCandidates.indexOf(client2.remoteAddress)); - assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); - assert.equal(common.PORT, client2.remotePort); - client2.end(); - }); -}); - -process.on('exit', function() { - assert.equal(2, conns); -}); diff --git a/test/simple/test-net-server-address.js b/test/simple/test-net-server-address.js deleted file mode 100644 index cc8fbd211..000000000 --- a/test/simple/test-net-server-address.js +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -// Test on IPv4 Server -var localhost_ipv4 = '127.0.0.1'; -var family_ipv4 = 'IPv4'; -var server_ipv4 = net.createServer(); - -server_ipv4.on('error', function(e) { - console.log('Error on ipv4 socket: ' + e.toString()); -}); - -server_ipv4.listen(common.PORT, localhost_ipv4, function() { - var address_ipv4 = server_ipv4.address(); - assert.strictEqual(address_ipv4.address, localhost_ipv4); - assert.strictEqual(address_ipv4.port, common.PORT); - assert.strictEqual(address_ipv4.family, family_ipv4); - server_ipv4.close(); -}); - -// Test on IPv6 Server -var localhost_ipv6 = '::1'; -var family_ipv6 = 'IPv6'; -var server_ipv6 = net.createServer(); - -server_ipv6.on('error', function(e) { - console.log('Error on ipv6 socket: ' + e.toString()); -}); - -server_ipv6.listen(common.PORT, localhost_ipv6, function() { - var address_ipv6 = server_ipv6.address(); - assert.strictEqual(address_ipv6.address, localhost_ipv6); - assert.strictEqual(address_ipv6.port, common.PORT); - assert.strictEqual(address_ipv6.family, family_ipv6); - server_ipv6.close(); -}); - -if (!common.hasIPv6) { - console.error('Skipping ipv6 part of test, no IPv6 support'); - return; -} - -// Test without hostname or ip -var anycast_ipv6 = '::'; -var server1 = net.createServer(); - -server1.on('error', function(e) { - console.log('Error on ip socket: ' + e.toString()); -}); - -// Specify the port number -server1.listen(common.PORT, function() { - var address = server1.address(); - assert.strictEqual(address.address, anycast_ipv6); - assert.strictEqual(address.port, common.PORT); - assert.strictEqual(address.family, family_ipv6); - server1.close(); -}); - -// Test without hostname or port -var server2 = net.createServer(); - -server2.on('error', function (e) { - console.log('Error on ip socket: ' + e.toString()); -}); - -// Don't specify the port number -server2.listen(function () { - var address = server2.address(); - assert.strictEqual(address.address, anycast_ipv6); - assert.strictEqual(address.family, family_ipv6); - server2.close(); -}); - -// Test without hostname, but with a false-y port -var server3 = net.createServer(); - -server3.on('error', function (e) { - console.log('Error on ip socket: ' + e.toString()); -}); - -// Specify a false-y port number -server3.listen(0, function () { - var address = server3.address(); - assert.strictEqual(address.address, anycast_ipv6); - assert.strictEqual(address.family, family_ipv6); - server3.close(); -}); - -// Test without hostname, but with port -1 -var server4 = net.createServer(); - -server4.on('error', function (e) { - console.log('Error on ip socket: ' + e.toString()); -}); - -// Specify -1 as port number -server4.listen(-1, function () { - var address = server4.address(); - assert.strictEqual(address.address, anycast_ipv6); - assert.strictEqual(address.family, family_ipv6); - server4.close(); -}); diff --git a/test/simple/test-net-server-bind.js b/test/simple/test-net-server-bind.js deleted file mode 100644 index 0951aa246..000000000 --- a/test/simple/test-net-server-bind.js +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - - -// With only a callback, server should get a port assigned by the OS - -var address0; -var server0 = net.createServer(function(socket) { }); - -server0.listen(function() { - address0 = server0.address(); - console.log('address0 %j', address0); - server0.close(); -}); - - -// No callback to listen(), assume we can bind in 100 ms - -var address1; -var server1 = net.createServer(function(socket) { }); - -server1.listen(common.PORT); - -setTimeout(function() { - address1 = server1.address(); - console.log('address1 %j', address1); - server1.close(); -}, 100); - - -// Callback to listen() - -var address2; -var server2 = net.createServer(function(socket) { }); - -server2.listen(common.PORT + 1, function() { - address2 = server2.address(); - console.log('address2 %j', address2); - server2.close(); -}); - - -// Backlog argument - -var address3; -var server3 = net.createServer(function(socket) { }); - -server3.listen(common.PORT + 2, '0.0.0.0', 127, function() { - address3 = server3.address(); - console.log('address3 %j', address3); - server3.close(); -}); - - -// Backlog argument without host argument - -var address4; -var server4 = net.createServer(function(socket) { }); - -server4.listen(common.PORT + 3, 127, function() { - address4 = server4.address(); - console.log('address4 %j', address4); - server4.close(); -}); - - -process.on('exit', function() { - assert.ok(address0.port > 100); - assert.equal(common.PORT, address1.port); - assert.equal(common.PORT + 1, address2.port); - assert.equal(common.PORT + 2, address3.port); - assert.equal(common.PORT + 3, address4.port); -}); diff --git a/test/simple/test-net-server-close.js b/test/simple/test-net-server-close.js deleted file mode 100644 index afa83f10d..000000000 --- a/test/simple/test-net-server-close.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var events = []; -var sockets = []; - -process.on('exit', function() { - assert.equal(server.connections, 0); - assert.equal(events.length, 3); - // Expect to see one server event and two client events. The order of the - // events is undefined because they arrive on the same event loop tick. - assert.equal(events.join(' ').match(/server/g).length, 1); - assert.equal(events.join(' ').match(/client/g).length, 2); -}); - -var server = net.createServer(function(c) { - c.on('close', function() { - events.push('client'); - }); - - sockets.push(c); - - if (sockets.length === 2) { - server.close(); - sockets.forEach(function(c) { c.destroy() }); - } -}); - -server.on('close', function() { - events.push('server'); -}); - -server.listen(common.PORT, function() { - net.createConnection(common.PORT); - net.createConnection(common.PORT); -}); diff --git a/test/simple/test-net-server-connections.js b/test/simple/test-net-server-connections.js deleted file mode 100644 index 423fcb8e3..000000000 --- a/test/simple/test-net-server-connections.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -// test that server.connections property is no longer enumerable now that it -// has been marked as deprecated - -var server = new net.Server(); - -assert.equal(Object.keys(server).indexOf('connections'), -1); diff --git a/test/simple/test-net-server-listen-remove-callback.js b/test/simple/test-net-server-listen-remove-callback.js deleted file mode 100644 index e10231de8..000000000 --- a/test/simple/test-net-server-listen-remove-callback.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -// Server should only fire listen callback once -var server = net.createServer(); - -server.on('close', function() { - var listeners = server.listeners('listening'); - console.log('Closed, listeners:', listeners.length); - assert.equal(0, listeners.length); -}); - -server.listen(common.PORT, function() { - server.close(); -}); - -server.once('close', function() { - server.listen(common.PORT + 1, function() { - server.close(); - }); -}); diff --git a/test/simple/test-net-server-max-connections.js b/test/simple/test-net-server-max-connections.js deleted file mode 100644 index 43bc2fee1..000000000 --- a/test/simple/test-net-server-max-connections.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -// This test creates 200 connections to a server and sets the server's -// maxConnections property to 100. The first 100 connections make it through -// and the last 100 connections are rejected. -// TODO: test that the server can accept more connections after it reaches -// its maximum and some are closed. - -var N = 200; -var count = 0; -var closes = 0; -var waits = []; - -var server = net.createServer(function(connection) { - console.error('connect %d', count++); - connection.write('hello'); - waits.push(function() { connection.end(); }); -}); - -server.listen(common.PORT, function() { - makeConnection(0); -}); - -server.maxConnections = N / 2; - -console.error('server.maxConnections = %d', server.maxConnections); - - -function makeConnection(index) { - var c = net.createConnection(common.PORT); - var gotData = false; - - c.on('connect', function() { - if (index + 1 < N) { - makeConnection(index + 1); - } - }); - - c.on('end', function() { c.end(); }); - - c.on('data', function(b) { - gotData = true; - assert.ok(0 < b.length); - }); - - c.on('error', function(e) { - console.error('error %d: %s', index, e); - }); - - c.on('close', function() { - console.error('closed %d', index); - closes++; - - if (closes < N / 2) { - assert.ok(server.maxConnections <= index, - index + - ' was one of the first closed connections ' + - 'but shouldnt have been'); - } - - if (closes === N / 2) { - var cb; - console.error('calling wait callback.'); - while (cb = waits.shift()) { - cb(); - } - server.close(); - } - - if (index < server.maxConnections) { - assert.equal(true, gotData, - index + ' didn\'t get data, but should have'); - } else { - assert.equal(false, gotData, - index + ' got data, but shouldn\'t have'); - } - }); -} - - -process.on('exit', function() { - assert.equal(N, closes); -}); diff --git a/test/simple/test-net-server-pause-on-connect.js b/test/simple/test-net-server-pause-on-connect.js deleted file mode 100644 index 3a8255e8f..000000000 --- a/test/simple/test-net-server-pause-on-connect.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var msg = 'test'; -var stopped = true; -var server1 = net.createServer({pauseOnConnect: true}, function(socket) { - socket.on('data', function(data) { - if (stopped) { - assert(false, 'data event should not have happened yet'); - } - - assert.equal(data.toString(), msg, 'invalid data received'); - socket.end(); - server1.close(); - }); - - setTimeout(function() { - assert.equal(socket.bytesRead, 0, 'no data should have been read yet'); - socket.resume(); - stopped = false; - }, 3000); -}); - -var server2 = net.createServer({pauseOnConnect: false}, function(socket) { - socket.on('data', function(data) { - assert.equal(data.toString(), msg, 'invalid data received'); - socket.end(); - server2.close(); - }); -}); - -server1.listen(common.PORT, function() { - net.createConnection({port: common.PORT}).write(msg); -}); - -server2.listen(common.PORT + 1, function() { - net.createConnection({port: common.PORT + 1}).write(msg); -}); diff --git a/test/simple/test-net-server-try-ports.js b/test/simple/test-net-server-try-ports.js deleted file mode 100644 index 5eca9d095..000000000 --- a/test/simple/test-net-server-try-ports.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This tests binds to one port, then attempts to start a server on that -// port. It should be EADDRINUSE but be able to then bind to another port. -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var connections = 0; - -var server1listening = false; -var server2listening = false; - -var server1 = net.Server(function(socket) { - connections++; - socket.destroy(); -}); - -var server2 = net.Server(function(socket) { - connections++; - socket.destroy(); -}); - -var server2errors = 0; -server2.on('error', function() { - server2errors++; - console.error('server2 error'); -}); - - -server1.listen(common.PORT, function() { - console.error('server1 listening'); - server1listening = true; - // This should make server2 emit EADDRINUSE - server2.listen(common.PORT); - - // Wait a bit, now try again. - // TODO, the listen callback should report if there was an error. - // Then we could avoid this very unlikely but potential race condition - // here. - setTimeout(function() { - server2.listen(common.PORT + 1, function() { - console.error('server2 listening'); - server2listening = true; - - server1.close(); - server2.close(); - }); - }, 100); -}); - - -process.on('exit', function() { - assert.equal(1, server2errors); - assert.ok(server2listening); - assert.ok(server1listening); -}); diff --git a/test/simple/test-net-server-unref.js b/test/simple/test-net-server-unref.js deleted file mode 100644 index d20cbe506..000000000 --- a/test/simple/test-net-server-unref.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); -var closed = false; - -var s = net.createServer(); -s.listen(); -s.unref(); - -setTimeout(function() { - closed = true; - s.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); -}); diff --git a/test/simple/test-net-settimeout.js b/test/simple/test-net-settimeout.js deleted file mode 100644 index da13385b9..000000000 --- a/test/simple/test-net-settimeout.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This example sets a timeout then immediately attempts to disable the timeout -// https://github.com/joyent/node/pull/2245 - -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - -var T = 100; - -var server = net.createServer(function(c) { - c.write('hello'); -}); -server.listen(common.PORT); - -var killers = [0, Infinity, NaN]; - -var left = killers.length; -killers.forEach(function(killer) { - var socket = net.createConnection(common.PORT, 'localhost'); - - socket.setTimeout(T, function() { - socket.destroy(); - if (--left === 0) server.close(); - assert.ok(killer !== 0); - clearTimeout(timeout); - }); - - socket.setTimeout(killer); - - var timeout = setTimeout(function() { - socket.destroy(); - if (--left === 0) server.close(); - assert.ok(killer === 0); - }, T * 2); -}); diff --git a/test/simple/test-net-socket-destroy-twice.js b/test/simple/test-net-socket-destroy-twice.js deleted file mode 100644 index 882e3a14c..000000000 --- a/test/simple/test-net-socket-destroy-twice.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var nerrors = 0; -var ncloses = 0; - -process.on('exit', function() { - assert.equal(nerrors, 1); - assert.equal(ncloses, 1); -}); - -var conn = net.createConnection(common.PORT); - -conn.on('error', function() { - nerrors++; - conn.destroy(); -}); - -conn.on('close', function() { - ncloses++; -}); diff --git a/test/simple/test-net-socket-timeout-unref.js b/test/simple/test-net-socket-timeout-unref.js deleted file mode 100644 index 32aef444a..000000000 --- a/test/simple/test-net-socket-timeout-unref.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var server = net.createServer(function (c) { - c.write('hello'); - c.unref(); -}); -server.listen(common.PORT); -server.unref(); - -var timedout = false; - -[8, 5, 3, 6, 2, 4].forEach(function (T) { - var socket = net.createConnection(common.PORT, 'localhost'); - socket.setTimeout(T * 1000, function () { - console.log(process._getActiveHandles()); - timedout = true; - socket.destroy(); - }); - socket.unref(); -}); - -process.on('exit', function () { - assert.strictEqual(timedout, false, 'Socket timeout should not hold loop open'); -}); diff --git a/test/simple/test-net-socket-timeout.js b/test/simple/test-net-socket-timeout.js deleted file mode 100644 index 2256d6813..000000000 --- a/test/simple/test-net-socket-timeout.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - -var timedout = false; - -var server = net.Server(); -server.listen(common.PORT, function() { - var socket = net.createConnection(common.PORT); - socket.setTimeout(100, function() { - timedout = true; - socket.destroy(); - server.close(); - clearTimeout(timer); - }); - var timer = setTimeout(function() { - process.exit(1); - }, 200); -}); - -process.on('exit', function() { - assert.ok(timedout); -}); diff --git a/test/simple/test-net-stream.js b/test/simple/test-net-stream.js deleted file mode 100644 index 9f2db51be..000000000 --- a/test/simple/test-net-stream.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); - -var s = new net.Stream(); - -// test that destroy called on a stream with a server only ever decrements the -// server connection count once - -s.server = new net.Server(); -s.server.connections = 10; - -assert.equal(10, s.server.connections); -s.destroy(); -assert.equal(9, s.server.connections); -s.destroy(); -assert.equal(9, s.server.connections); - -var SIZE = 2E6; -var N = 10; -var buf = new Buffer(SIZE); -buf.fill(0x61); // 'a' - -var server = net.createServer(function(socket) { - socket.setNoDelay(); - - socket.on('error', function(err) { - socket.destroy(); - }).on('close', function() { - server.close(); - }) - - for (var i = 0; i < N; ++i) { - socket.write(buf, function() { }); - } - socket.end(); - -}).listen(common.PORT, function() { - var conn = net.connect(common.PORT); - conn.on('data', function(buf) { - conn.pause(); - setTimeout(function() { - conn.destroy(); - }, 20); - }); - }); - -process.on('exit', function() { - assert.equal(server.connections, 0); -}); diff --git a/test/simple/test-net-write-after-close.js b/test/simple/test-net-write-after-close.js deleted file mode 100644 index 3b98bbc42..000000000 --- a/test/simple/test-net-write-after-close.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var gotError = false; -var gotWriteCB = false; - -process.on('exit', function() { - assert(gotError); - assert(gotWriteCB); -}); - -var server = net.createServer(function(socket) { - socket.resume(); - - socket.on('error', function(error) { - console.error('got error, closing server', error); - server.close(); - gotError = true; - }); - - setTimeout(function() { - console.error('about to try to write'); - socket.write('test', function(e) { - gotWriteCB = true; - }); - }, 250); -}); - -server.listen(common.PORT, function() { - var client = net.connect(common.PORT, function() { - client.end(); - }); -}); diff --git a/test/simple/test-net-write-connect-write.js b/test/simple/test-net-write-connect-write.js deleted file mode 100644 index cb65af8a8..000000000 --- a/test/simple/test-net-write-connect-write.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var received = ''; - -var server = net.createServer(function(socket) { - socket.pipe(socket); -}).listen(common.PORT, function() { - var conn = net.connect(common.PORT); - conn.setEncoding('utf8'); - conn.write('before'); - conn.on('connect', function() { - conn.write('after'); - }); - conn.on('data', function(buf) { - received += buf; - conn.end(); - }); - conn.on('end', function() { - server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(received, 'before' + 'after'); -}); diff --git a/test/simple/test-net-write-slow.js b/test/simple/test-net-write-slow.js deleted file mode 100644 index 468c311c5..000000000 --- a/test/simple/test-net-write-slow.js +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var SIZE = 2E5; -var N = 10; -var flushed = 0; -var received = 0; -var buf = new Buffer(SIZE); -buf.fill(0x61); // 'a' - -var server = net.createServer(function(socket) { - socket.setNoDelay(); - socket.setTimeout(1000); - socket.on('timeout', function() { - assert.fail('flushed: ' + flushed + - ', received: ' + received + '/' + SIZE * N); - }); - - for (var i = 0; i < N; ++i) { - socket.write(buf, function() { - ++flushed; - if (flushed === N) { - socket.setTimeout(0); - } - }); - } - socket.end(); - -}).listen(common.PORT, function() { - var conn = net.connect(common.PORT); - conn.on('data', function(buf) { - received += buf.length; - conn.pause(); - setTimeout(function() { - conn.resume(); - }, 20); - }); - conn.on('end', function() { - server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(received, SIZE * N); -}); diff --git a/test/simple/test-next-tick-doesnt-hang.js b/test/simple/test-next-tick-doesnt-hang.js deleted file mode 100644 index 3d26bd3c6..000000000 --- a/test/simple/test-next-tick-doesnt-hang.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -/* - * This test verifies that having a single nextTick statement and nothing else - * does not hang the event loop. If this test times out it has failed. - */ - -process.nextTick(function() { - // Nothing -}); diff --git a/test/simple/test-next-tick-domain.js b/test/simple/test-next-tick-domain.js deleted file mode 100644 index 16f77ed94..000000000 --- a/test/simple/test-next-tick-domain.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var origNextTick = process.nextTick; - -require('domain'); - -assert.strictEqual(origNextTick, process.nextTick, 'Requiring domain should not change nextTick'); diff --git a/test/simple/test-next-tick-error-spin.js b/test/simple/test-next-tick-error-spin.js deleted file mode 100644 index e0d47a214..000000000 --- a/test/simple/test-next-tick-error-spin.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -if (process.argv[2] !== 'child') { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { - stdio: 'pipe'//'inherit' - }); - var timer = setTimeout(function() { - throw new Error('child is hung'); - }, 3000); - child.on('exit', function(code) { - console.error('ok'); - assert(!code); - clearTimeout(timer); - }); -} else { - - var domain = require('domain'); - var d = domain.create(); - process.maxTickDepth = 10; - - // in the error handler, we trigger several MakeCallback events - d.on('error', function(e) { - console.log('a') - console.log('b') - console.log('c') - console.log('d') - console.log('e') - f(); - }); - - function f() { - process.nextTick(function() { - d.run(function() { - throw(new Error('x')); - }); - }); - } - - f(); - setTimeout(function () { - console.error('broke in!'); - //process.stdout.close(); - //process.stderr.close(); - process.exit(0); - }); -} diff --git a/test/simple/test-next-tick-errors.js b/test/simple/test-next-tick-errors.js deleted file mode 100644 index bf3c2e306..000000000 --- a/test/simple/test-next-tick-errors.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var order = [], - exceptionHandled = false; - -// This nextTick function will throw an error. It should only be called once. -// When it throws an error, it should still get removed from the queue. -process.nextTick(function() { - order.push('A'); - // cause an error - what(); -}); - -// This nextTick function should remain in the queue when the first one -// is removed. It should be called if the error in the first one is -// caught (which we do in this test). -process.nextTick(function() { - order.push('C'); -}); - -process.on('uncaughtException', function() { - if (!exceptionHandled) { - exceptionHandled = true; - order.push('B'); - } - else { - // If we get here then the first process.nextTick got called twice - order.push('OOPS!'); - } -}); - -process.on('exit', function() { - assert.deepEqual(['A', 'B', 'C'], order); -}); - diff --git a/test/simple/test-next-tick-intentional-starvation.js b/test/simple/test-next-tick-intentional-starvation.js deleted file mode 100644 index 1a76b27e4..000000000 --- a/test/simple/test-next-tick-intentional-starvation.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// this is the inverse of test-next-tick-starvation. -// it verifies that process.nextTick will *always* come before other -// events, up to the limit of the process.maxTickDepth value. - -// WARNING: unsafe! -process.maxTickDepth = Infinity; - -var ran = false; -var starved = false; -var start = +new Date(); -var timerRan = false; - -function spin() { - ran = true; - var now = +new Date(); - if (now - start > 100) { - console.log('The timer is starving, just as we planned.'); - starved = true; - - // now let it out. - return; - } - - process.nextTick(spin); -} - -function onTimeout() { - if (!starved) throw new Error('The timer escaped!'); - console.log('The timer ran once the ban was lifted'); - timerRan = true; -} - -spin(); -setTimeout(onTimeout, 50); - -process.on('exit', function() { - assert.ok(ran); - assert.ok(starved); - assert.ok(timerRan); -}); diff --git a/test/simple/test-next-tick-ordering.js b/test/simple/test-next-tick-ordering.js deleted file mode 100644 index 5dc1dfbe1..000000000 --- a/test/simple/test-next-tick-ordering.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var i; - -var N = 30; -var done = []; - -function get_printer(timeout) { - return function() { - console.log('Running from setTimeout ' + timeout); - done.push(timeout); - }; -} - -process.nextTick(function() { - console.log('Running from nextTick'); - done.push('nextTick'); -}); - -for (i = 0; i < N; i += 1) { - setTimeout(get_printer(i), i); -} - -console.log('Running from main.'); - - -process.on('exit', function() { - assert.equal('nextTick', done[0]); - /* Disabling this test. I don't think we can ensure the order - for (i = 0; i < N; i += 1) { - assert.equal(i, done[i + 1]); - } - */ -}); diff --git a/test/simple/test-next-tick-ordering2.js b/test/simple/test-next-tick-ordering2.js deleted file mode 100644 index 94fd20fbb..000000000 --- a/test/simple/test-next-tick-ordering2.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var order = []; -process.nextTick(function() { - setTimeout(function() { - order.push('setTimeout'); - }, 0); - - process.nextTick(function() { - order.push('nextTick'); - }); -}); - -process.on('exit', function() { - assert.deepEqual(order, ['nextTick', 'setTimeout']); -}); diff --git a/test/simple/test-next-tick.js b/test/simple/test-next-tick.js deleted file mode 100644 index 2e40658c9..000000000 --- a/test/simple/test-next-tick.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var complete = 0; - -process.nextTick(function() { - complete++; - process.nextTick(function() { - complete++; - process.nextTick(function() { - complete++; - }); - }); -}); - -setTimeout(function() { - process.nextTick(function() { - complete++; - }); -}, 50); - -process.nextTick(function() { - complete++; -}); - -process.on('exit', function() { - assert.equal(5, complete); - process.nextTick(function() { - throw new Error('this should not occur'); - }); -}); diff --git a/test/simple/test-os.js b/test/simple/test-os.js deleted file mode 100644 index 5763e071b..000000000 --- a/test/simple/test-os.js +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var os = require('os'); - - -process.env.TMPDIR = '/tmpdir'; -process.env.TMP = '/tmp'; -process.env.TEMP = '/temp'; -if (process.platform === 'win32') { - assert.equal(os.tmpdir(), '/temp'); - process.env.TEMP = ''; - assert.equal(os.tmpdir(), '/tmp'); - process.env.TMP = ''; - var expected = (process.env.SystemRoot || process.env.windir) + '\\temp'; - assert.equal(os.tmpdir(), expected); -} else { - assert.equal(os.tmpdir(), '/tmpdir'); - process.env.TMPDIR = ''; - assert.equal(os.tmpdir(), '/tmp'); - process.env.TMP = ''; - assert.equal(os.tmpdir(), '/temp'); - process.env.TEMP = ''; - assert.equal(os.tmpdir(), '/tmp'); -} - -var endianness = os.endianness(); -console.log('endianness = %s', endianness); -assert.ok(/[BL]E/.test(endianness)); - -var hostname = os.hostname(); -console.log('hostname = %s', hostname); -assert.ok(hostname.length > 0); - -var uptime = os.uptime(); -console.log('uptime = %d', uptime); -assert.ok(uptime > 0); - -var cpus = os.cpus(); -console.log('cpus = ', cpus); -assert.ok(cpus.length > 0); - -var type = os.type(); -console.log('type = ', type); -assert.ok(type.length > 0); - -var release = os.release(); -console.log('release = ', release); -assert.ok(release.length > 0); - -var platform = os.platform(); -console.log('platform = ', platform); -assert.ok(platform.length > 0); - -var arch = os.arch(); -console.log('arch = ', arch); -assert.ok(arch.length > 0); - -if (process.platform != 'sunos') { - // not implemeneted yet - assert.ok(os.loadavg().length > 0); - assert.ok(os.freemem() > 0); - assert.ok(os.totalmem() > 0); -} - - -var interfaces = os.networkInterfaces(); -console.error(interfaces); -switch (platform) { - case 'linux': - var filter = function(e) { return e.address == '127.0.0.1'; }; - var actual = interfaces.lo.filter(filter); - var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', - mac: '00:00:00:00:00:00', family: 'IPv4', - internal: true }]; - assert.deepEqual(actual, expected); - break; - case 'win32': - var filter = function(e) { return e.address == '127.0.0.1'; }; - var actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); - var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', - mac: '00:00:00:00:00:00', family: 'IPv4', - internal: true }]; - assert.deepEqual(actual, expected); - break; -} - -var EOL = os.EOL; -assert.ok(EOL.length > 0); diff --git a/test/simple/test-path-makelong.js b/test/simple/test-path-makelong.js deleted file mode 100644 index d9d8efd40..000000000 --- a/test/simple/test-path-makelong.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var path = require('path'); -var common = require('../common'); - -if (process.platform === 'win32') { - var file = path.join(common.fixturesDir, 'a.js'); - var resolvedFile = path.resolve(file); - - assert.equal('\\\\?\\' + resolvedFile, path._makeLong(file)); - assert.equal('\\\\?\\' + resolvedFile, path._makeLong('\\\\?\\' + file)); - assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', - path._makeLong('\\\\someserver\\someshare\\somefile')); - assert.equal('\\\\?\\UNC\\someserver\\someshare\\somefile', - path._makeLong('\\\\?\\UNC\\someserver\\someshare\\somefile')); - assert.equal('\\\\.\\pipe\\somepipe', - path._makeLong('\\\\.\\pipe\\somepipe')); -} - -assert.equal(path._makeLong(null), null); -assert.equal(path._makeLong(100), 100); -assert.equal(path._makeLong(path), path); -assert.equal(path._makeLong(false), false); -assert.equal(path._makeLong(true), true); diff --git a/test/simple/test-path-parse-format.js b/test/simple/test-path-parse-format.js deleted file mode 100644 index 4f6e5af45..000000000 --- a/test/simple/test-path-parse-format.js +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var path = require('path'); - -var winPaths = [ - 'C:\\path\\dir\\index.html', - 'C:\\another_path\\DIR\\1\\2\\33\\index', - 'another_path\\DIR with spaces\\1\\2\\33\\index', - '\\foo\\C:', - 'file', - '.\\file', - - // unc - '\\\\server\\share\\file_path', - '\\\\server two\\shared folder\\file path.zip', - '\\\\teela\\admin$\\system32', - '\\\\?\\UNC\\server\\share' - -]; - -var unixPaths = [ - '/home/user/dir/file.txt', - '/home/user/a dir/another File.zip', - '/home/user/a dir//another&File.', - '/home/user/a$$$dir//another File.zip', - 'user/dir/another File.zip', - 'file', - '.\\file', - './file', - 'C:\\foo' -]; - -var errors = [ - {method: 'parse', input: [null], message: /Parameter 'pathString' must be a string, not/}, - {method: 'parse', input: [{}], message: /Parameter 'pathString' must be a string, not object/}, - {method: 'parse', input: [true], message: /Parameter 'pathString' must be a string, not boolean/}, - {method: 'parse', input: [1], message: /Parameter 'pathString' must be a string, not number/}, - {method: 'parse', input: [], message: /Parameter 'pathString' must be a string, not undefined/}, - // {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger! - {method: 'format', input: [null], message: /Parameter 'pathObject' must be an object, not/}, - {method: 'format', input: [''], message: /Parameter 'pathObject' must be an object, not string/}, - {method: 'format', input: [true], message: /Parameter 'pathObject' must be an object, not boolean/}, - {method: 'format', input: [1], message: /Parameter 'pathObject' must be an object, not number/}, - {method: 'format', input: [{root: true}], message: /'pathObject.root' must be a string or undefined, not boolean/}, - {method: 'format', input: [{root: 12}], message: /'pathObject.root' must be a string or undefined, not number/}, -]; - -check(path.win32, winPaths); -check(path.posix, unixPaths); -checkErrors(path.win32); -checkErrors(path.posix); - -function checkErrors(path) { - errors.forEach(function(errorCase) { - try { - path[errorCase.method].apply(path, errorCase.input); - } catch(err) { - assert.ok(err instanceof TypeError); - assert.ok( - errorCase.message.test(err.message), - 'expected ' + errorCase.message + ' to match ' + err.message - ); - return; - } - - assert.fail('should have thrown'); - }); -} - - -function check(path, paths) { - paths.forEach(function(element, index, array) { - var output = path.parse(element); - assert.strictEqual(path.format(output), element); - assert.strictEqual(output.dir, output.dir ? path.dirname(element) : ''); - assert.strictEqual(output.base, path.basename(element)); - assert.strictEqual(output.ext, path.extname(element)); - }); -} diff --git a/test/simple/test-path.js b/test/simple/test-path.js deleted file mode 100644 index 7a8a1b14a..000000000 --- a/test/simple/test-path.js +++ /dev/null @@ -1,412 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var path = require('path'); - -var isWindows = process.platform === 'win32'; - -var f = __filename; - -assert.equal(path.basename(f), 'test-path.js'); -assert.equal(path.basename(f, '.js'), 'test-path'); -assert.equal(path.basename(''), ''); -assert.equal(path.basename('/dir/basename.ext'), 'basename.ext'); -assert.equal(path.basename('/basename.ext'), 'basename.ext'); -assert.equal(path.basename('basename.ext'), 'basename.ext'); -assert.equal(path.basename('basename.ext/'), 'basename.ext'); -assert.equal(path.basename('basename.ext//'), 'basename.ext'); - -// On Windows a backslash acts as a path separator. -assert.equal(path.win32.basename('\\dir\\basename.ext'), 'basename.ext'); -assert.equal(path.win32.basename('\\basename.ext'), 'basename.ext'); -assert.equal(path.win32.basename('basename.ext'), 'basename.ext'); -assert.equal(path.win32.basename('basename.ext\\'), 'basename.ext'); -assert.equal(path.win32.basename('basename.ext\\\\'), 'basename.ext'); - -// On unix a backslash is just treated as any other character. -assert.equal(path.posix.basename('\\dir\\basename.ext'), '\\dir\\basename.ext'); -assert.equal(path.posix.basename('\\basename.ext'), '\\basename.ext'); -assert.equal(path.posix.basename('basename.ext'), 'basename.ext'); -assert.equal(path.posix.basename('basename.ext\\'), 'basename.ext\\'); -assert.equal(path.posix.basename('basename.ext\\\\'), 'basename.ext\\\\'); - -// POSIX filenames may include control characters -// c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html -if (!isWindows) { - var controlCharFilename = 'Icon' + String.fromCharCode(13); - assert.equal(path.basename('/a/b/' + controlCharFilename), - controlCharFilename); -} - -assert.equal(path.extname(f), '.js'); - -assert.equal(path.dirname(f).substr(-11), - isWindows ? 'test\\simple' : 'test/simple'); -assert.equal(path.dirname('/a/b/'), '/a'); -assert.equal(path.dirname('/a/b'), '/a'); -assert.equal(path.dirname('/a'), '/'); -assert.equal(path.dirname(''), '.'); -assert.equal(path.dirname('/'), '/'); -assert.equal(path.dirname('////'), '/'); - -assert.equal(path.win32.dirname('c:\\'), 'c:\\'); -assert.equal(path.win32.dirname('c:\\foo'), 'c:\\'); -assert.equal(path.win32.dirname('c:\\foo\\'), 'c:\\'); -assert.equal(path.win32.dirname('c:\\foo\\bar'), 'c:\\foo'); -assert.equal(path.win32.dirname('c:\\foo\\bar\\'), 'c:\\foo'); -assert.equal(path.win32.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar'); -assert.equal(path.win32.dirname('\\'), '\\'); -assert.equal(path.win32.dirname('\\foo'), '\\'); -assert.equal(path.win32.dirname('\\foo\\'), '\\'); -assert.equal(path.win32.dirname('\\foo\\bar'), '\\foo'); -assert.equal(path.win32.dirname('\\foo\\bar\\'), '\\foo'); -assert.equal(path.win32.dirname('\\foo\\bar\\baz'), '\\foo\\bar'); -assert.equal(path.win32.dirname('c:'), 'c:'); -assert.equal(path.win32.dirname('c:foo'), 'c:'); -assert.equal(path.win32.dirname('c:foo\\'), 'c:'); -assert.equal(path.win32.dirname('c:foo\\bar'), 'c:foo'); -assert.equal(path.win32.dirname('c:foo\\bar\\'), 'c:foo'); -assert.equal(path.win32.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); -assert.equal(path.win32.dirname('\\\\unc\\share'), '\\\\unc\\share'); -assert.equal(path.win32.dirname('\\\\unc\\share\\foo'), '\\\\unc\\share\\'); -assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\'), '\\\\unc\\share\\'); -assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar'), - '\\\\unc\\share\\foo'); -assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar\\'), - '\\\\unc\\share\\foo'); -assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar\\baz'), - '\\\\unc\\share\\foo\\bar'); - - -assert.equal(path.extname(''), ''); -assert.equal(path.extname('/path/to/file'), ''); -assert.equal(path.extname('/path/to/file.ext'), '.ext'); -assert.equal(path.extname('/path.to/file.ext'), '.ext'); -assert.equal(path.extname('/path.to/file'), ''); -assert.equal(path.extname('/path.to/.file'), ''); -assert.equal(path.extname('/path.to/.file.ext'), '.ext'); -assert.equal(path.extname('/path/to/f.ext'), '.ext'); -assert.equal(path.extname('/path/to/..ext'), '.ext'); -assert.equal(path.extname('file'), ''); -assert.equal(path.extname('file.ext'), '.ext'); -assert.equal(path.extname('.file'), ''); -assert.equal(path.extname('.file.ext'), '.ext'); -assert.equal(path.extname('/file'), ''); -assert.equal(path.extname('/file.ext'), '.ext'); -assert.equal(path.extname('/.file'), ''); -assert.equal(path.extname('/.file.ext'), '.ext'); -assert.equal(path.extname('.path/file.ext'), '.ext'); -assert.equal(path.extname('file.ext.ext'), '.ext'); -assert.equal(path.extname('file.'), '.'); -assert.equal(path.extname('.'), ''); -assert.equal(path.extname('./'), ''); -assert.equal(path.extname('.file.ext'), '.ext'); -assert.equal(path.extname('.file'), ''); -assert.equal(path.extname('.file.'), '.'); -assert.equal(path.extname('.file..'), '.'); -assert.equal(path.extname('..'), ''); -assert.equal(path.extname('../'), ''); -assert.equal(path.extname('..file.ext'), '.ext'); -assert.equal(path.extname('..file'), '.file'); -assert.equal(path.extname('..file.'), '.'); -assert.equal(path.extname('..file..'), '.'); -assert.equal(path.extname('...'), '.'); -assert.equal(path.extname('...ext'), '.ext'); -assert.equal(path.extname('....'), '.'); -assert.equal(path.extname('file.ext/'), '.ext'); -assert.equal(path.extname('file.ext//'), '.ext'); -assert.equal(path.extname('file/'), ''); -assert.equal(path.extname('file//'), ''); -assert.equal(path.extname('file./'), '.'); -assert.equal(path.extname('file.//'), '.'); - -// On windows, backspace is a path separator. -assert.equal(path.win32.extname('.\\'), ''); -assert.equal(path.win32.extname('..\\'), ''); -assert.equal(path.win32.extname('file.ext\\'), '.ext'); -assert.equal(path.win32.extname('file.ext\\\\'), '.ext'); -assert.equal(path.win32.extname('file\\'), ''); -assert.equal(path.win32.extname('file\\\\'), ''); -assert.equal(path.win32.extname('file.\\'), '.'); -assert.equal(path.win32.extname('file.\\\\'), '.'); - -// On unix, backspace is a valid name component like any other character. -assert.equal(path.posix.extname('.\\'), ''); -assert.equal(path.posix.extname('..\\'), '.\\'); -assert.equal(path.posix.extname('file.ext\\'), '.ext\\'); -assert.equal(path.posix.extname('file.ext\\\\'), '.ext\\\\'); -assert.equal(path.posix.extname('file\\'), ''); -assert.equal(path.posix.extname('file\\\\'), ''); -assert.equal(path.posix.extname('file.\\'), '.\\'); -assert.equal(path.posix.extname('file.\\\\'), '.\\\\'); - -// path.join tests -var failures = []; -var joinTests = - // arguments result - [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], - [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], - [['/foo', '../../../bar'], '/bar'], - [['foo', '../../../bar'], '../../bar'], - [['foo/', '../../../bar'], '../../bar'], - [['foo/x', '../../../bar'], '../bar'], - [['foo/x', './bar'], 'foo/x/bar'], - [['foo/x/', './bar'], 'foo/x/bar'], - [['foo/x/', '.', 'bar'], 'foo/x/bar'], - [['./'], './'], - [['.', './'], './'], - [['.', '.', '.'], '.'], - [['.', './', '.'], '.'], - [['.', '/./', '.'], '.'], - [['.', '/////./', '.'], '.'], - [['.'], '.'], - [['', '.'], '.'], - [['', 'foo'], 'foo'], - [['foo', '/bar'], 'foo/bar'], - [['', '/foo'], '/foo'], - [['', '', '/foo'], '/foo'], - [['', '', 'foo'], 'foo'], - [['foo', ''], 'foo'], - [['foo/', ''], 'foo/'], - [['foo', '', '/bar'], 'foo/bar'], - [['./', '..', '/foo'], '../foo'], - [['./', '..', '..', '/foo'], '../../foo'], - [['.', '..', '..', '/foo'], '../../foo'], - [['', '..', '..', '/foo'], '../../foo'], - [['/'], '/'], - [['/', '.'], '/'], - [['/', '..'], '/'], - [['/', '..', '..'], '/'], - [[''], '.'], - [['', ''], '.'], - [[' /foo'], ' /foo'], - [[' ', 'foo'], ' /foo'], - [[' ', '.'], ' '], - [[' ', '/'], ' /'], - [[' ', ''], ' '], - [['/', 'foo'], '/foo'], - [['/', '/foo'], '/foo'], - [['/', '//foo'], '/foo'], - [['/', '', '/foo'], '/foo'], - [['', '/', 'foo'], '/foo'], - [['', '/', '/foo'], '/foo'] - ]; - -// Windows-specific join tests -if (isWindows) { - joinTests = joinTests.concat( - [// UNC path expected - [['//foo/bar'], '//foo/bar/'], - [['\\/foo/bar'], '//foo/bar/'], - [['\\\\foo/bar'], '//foo/bar/'], - // UNC path expected - server and share separate - [['//foo', 'bar'], '//foo/bar/'], - [['//foo/', 'bar'], '//foo/bar/'], - [['//foo', '/bar'], '//foo/bar/'], - // UNC path expected - questionable - [['//foo', '', 'bar'], '//foo/bar/'], - [['//foo/', '', 'bar'], '//foo/bar/'], - [['//foo/', '', '/bar'], '//foo/bar/'], - // UNC path expected - even more questionable - [['', '//foo', 'bar'], '//foo/bar/'], - [['', '//foo/', 'bar'], '//foo/bar/'], - [['', '//foo/', '/bar'], '//foo/bar/'], - // No UNC path expected (no double slash in first component) - [['\\', 'foo/bar'], '/foo/bar'], - [['\\', '/foo/bar'], '/foo/bar'], - [['', '/', '/foo/bar'], '/foo/bar'], - // No UNC path expected (no non-slashes in first component - questionable) - [['//', 'foo/bar'], '/foo/bar'], - [['//', '/foo/bar'], '/foo/bar'], - [['\\\\', '/', '/foo/bar'], '/foo/bar'], - [['//'], '/'], - // No UNC path expected (share name missing - questionable). - [['//foo'], '/foo'], - [['//foo/'], '/foo/'], - [['//foo', '/'], '/foo/'], - [['//foo', '', '/'], '/foo/'], - // No UNC path expected (too many leading slashes - questionable) - [['///foo/bar'], '/foo/bar'], - [['////foo', 'bar'], '/foo/bar'], - [['\\\\\\/foo/bar'], '/foo/bar'], - // Drive-relative vs drive-absolute paths. This merely describes the - // status quo, rather than being obviously right - [['c:'], 'c:.'], - [['c:.'], 'c:.'], - [['c:', ''], 'c:.'], - [['', 'c:'], 'c:.'], - [['c:.', '/'], 'c:./'], - [['c:.', 'file'], 'c:file'], - [['c:', '/'], 'c:/'], - [['c:', 'file'], 'c:/file'] - ]); -} - -// Run the join tests. -joinTests.forEach(function(test) { - var actual = path.join.apply(path, test[0]); - var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1]; - var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' + - '\n expect=' + JSON.stringify(expected) + - '\n actual=' + JSON.stringify(actual); - if (actual !== expected) failures.push('\n' + message); - // assert.equal(actual, expected, message); -}); -assert.equal(failures.length, 0, failures.join('')); -var joinThrowTests = [true, false, 7, null, {}, undefined, [], NaN]; -joinThrowTests.forEach(function(test) { - assert.throws(function() { - path.join(test); - }, TypeError); - assert.throws(function() { - path.resolve(test); - }, TypeError); -}); - - -// path normalize tests -assert.equal(path.win32.normalize('./fixtures///b/../b/c.js'), - 'fixtures\\b\\c.js'); -assert.equal(path.win32.normalize('/foo/../../../bar'), '\\bar'); -assert.equal(path.win32.normalize('a//b//../b'), 'a\\b'); -assert.equal(path.win32.normalize('a//b//./c'), 'a\\b\\c'); -assert.equal(path.win32.normalize('a//b//.'), 'a\\b'); -assert.equal(path.win32.normalize('//server/share/dir/file.ext'), - '\\\\server\\share\\dir\\file.ext'); - -assert.equal(path.posix.normalize('./fixtures///b/../b/c.js'), - 'fixtures/b/c.js'); -assert.equal(path.posix.normalize('/foo/../../../bar'), '/bar'); -assert.equal(path.posix.normalize('a//b//../b'), 'a/b'); -assert.equal(path.posix.normalize('a//b//./c'), 'a/b/c'); -assert.equal(path.posix.normalize('a//b//.'), 'a/b'); - -// path.resolve tests -if (isWindows) { - // windows - var resolveTests = - // arguments result - [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], - [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], - [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], - [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], - [['.'], process.cwd()], - [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], - [['c:/', '//'], 'c:\\'], - [['c:/', '//dir'], 'c:\\dir'], - [['c:/', '//server/share'], '\\\\server\\share\\'], - [['c:/', '//server//share'], '\\\\server\\share\\'], - [['c:/', '///some//dir'], 'c:\\some\\dir'] - ]; -} else { - // Posix - var resolveTests = - // arguments result - [[['/var/lib', '../', 'file/'], '/var/file'], - [['/var/lib', '/../', 'file/'], '/file'], - [['a/b/c/', '../../..'], process.cwd()], - [['.'], process.cwd()], - [['/some/dir', '.', '/absolute/'], '/absolute']]; -} -var failures = []; -resolveTests.forEach(function(test) { - var actual = path.resolve.apply(path, test[0]); - var expected = test[1]; - var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' + - '\n expect=' + JSON.stringify(expected) + - '\n actual=' + JSON.stringify(actual); - if (actual !== expected) failures.push('\n' + message); - // assert.equal(actual, expected, message); -}); -assert.equal(failures.length, 0, failures.join('')); - -// path.isAbsolute tests -assert.equal(path.win32.isAbsolute('//server/file'), true); -assert.equal(path.win32.isAbsolute('\\\\server\\file'), true); -assert.equal(path.win32.isAbsolute('C:/Users/'), true); -assert.equal(path.win32.isAbsolute('C:\\Users\\'), true); -assert.equal(path.win32.isAbsolute('C:cwd/another'), false); -assert.equal(path.win32.isAbsolute('C:cwd\\another'), false); -assert.equal(path.win32.isAbsolute('directory/directory'), false); -assert.equal(path.win32.isAbsolute('directory\\directory'), false); - -assert.equal(path.posix.isAbsolute('/home/foo'), true); -assert.equal(path.posix.isAbsolute('/home/foo/..'), true); -assert.equal(path.posix.isAbsolute('bar/'), false); -assert.equal(path.posix.isAbsolute('./baz'), false); - -// path.relative tests -if (isWindows) { - // windows - var relativeTests = - // arguments result - [['c:/blah\\blah', 'd:/games', 'd:\\games'], - ['c:/aaaa/bbbb', 'c:/aaaa', '..'], - ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], - ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], - ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], - ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], - ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], - ['c:/aaaa/bbbb', 'd:\\', 'd:\\']]; -} else { - // posix - var relativeTests = - // arguments result - [['/var/lib', '/var', '..'], - ['/var/lib', '/bin', '../../bin'], - ['/var/lib', '/var/lib', ''], - ['/var/lib', '/var/apache', '../apache'], - ['/var/', '/var/lib', 'lib'], - ['/', '/var/lib', 'var/lib']]; -} -var failures = []; -relativeTests.forEach(function(test) { - var actual = path.relative(test[0], test[1]); - var expected = test[2]; - var message = 'path.relative(' + - test.slice(0, 2).map(JSON.stringify).join(',') + - ')' + - '\n expect=' + JSON.stringify(expected) + - '\n actual=' + JSON.stringify(actual); - if (actual !== expected) failures.push('\n' + message); -}); -assert.equal(failures.length, 0, failures.join('')); - -// windows -assert.equal(path.win32.sep, '\\'); -// posix -assert.equal(path.posix.sep, '/'); - -// path.delimiter tests -// windows -assert.equal(path.win32.delimiter, ';'); - -// posix -assert.equal(path.posix.delimiter, ':'); - - -if (isWindows) - assert.deepEqual(path, path.win32, 'should be win32 path module'); -else - assert.deepEqual(path, path.posix, 'should be posix path module'); diff --git a/test/simple/test-pipe-address.js b/test/simple/test-pipe-address.js deleted file mode 100644 index 6b29d2a2c..000000000 --- a/test/simple/test-pipe-address.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -var address = null; - -var server = net.createServer(function() { - assert(false); // should not be called -}); - -server.listen(common.PIPE, function() { - address = server.address(); - server.close(); -}); - -process.on('exit', function() { - assert.equal(address, common.PIPE); -}); diff --git a/test/simple/test-pipe-file-to-http.js b/test/simple/test-pipe-file-to-http.js deleted file mode 100644 index 1b3ba7089..000000000 --- a/test/simple/test-pipe-file-to-http.js +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var http = require('http'); -var path = require('path'); -var cp = require('child_process'); - -var filename = path.join(common.tmpDir || '/tmp', 'big'); -var clientReqComplete = false; -var count = 0; - -var server = http.createServer(function(req, res) { - console.error('SERVER request'); - var timeoutId; - assert.equal('POST', req.method); - req.pause(); - common.error('request paused'); - - setTimeout(function() { - req.resume(); - common.error('request resumed'); - }, 1000); - - req.on('data', function(chunk) { - common.error('recv data! nchars = ' + chunk.length); - count += chunk.length; - }); - - req.on('end', function() { - if (timeoutId) { - clearTimeout(timeoutId); - } - console.log('request complete from server'); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end(); - }); -}); -server.listen(common.PORT); - -server.on('listening', function() { - var cmd = common.ddCommand(filename, 10240); - console.log('dd command: ', cmd); - - cp.exec(cmd, function(err, stdout, stderr) { - if (err) throw err; - console.error('EXEC returned successfully stdout=%d stderr=%d', - stdout.length, stderr.length); - makeRequest(); - }); -}); - -function makeRequest() { - var req = http.request({ - port: common.PORT, - path: '/', - method: 'POST' - }); - - common.error('pipe!'); - - var s = fs.ReadStream(filename); - s.pipe(req); - s.on('data', function(chunk) { - console.error('FS data chunk=%d', chunk.length); - }); - s.on('end', function() { - console.error('FS end'); - }); - s.on('close', function(err) { - if (err) throw err; - clientReqComplete = true; - common.error('client finished sending request'); - }); - - req.on('response', function(res) { - console.error('RESPONSE', res.statusCode, res.headers); - res.resume(); - res.on('end', function() { - console.error('RESPONSE end'); - server.close(); - }); - }); -} - -process.on('exit', function() { - assert.equal(1024 * 10240, count); - assert.ok(clientReqComplete); -}); diff --git a/test/simple/test-pipe-head.js b/test/simple/test-pipe-head.js deleted file mode 100644 index a049be6c2..000000000 --- a/test/simple/test-pipe-head.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var exec = require('child_process').exec; -var join = require('path').join; - -var nodePath = process.argv[0]; -var script = join(common.fixturesDir, 'print-10-lines.js'); - -var cmd = '"' + nodePath + '" "' + script + '" | head -2'; - -var finished = false; - -exec(cmd, function(err, stdout, stderr) { - if (err) throw err; - var lines = stdout.split('\n'); - assert.equal(3, lines.length); - finished = true; -}); - - -process.on('exit', function() { - assert.ok(finished); -}); diff --git a/test/simple/test-pipe-return-val.js b/test/simple/test-pipe-return-val.js deleted file mode 100644 index 274e9f5bc..000000000 --- a/test/simple/test-pipe-return-val.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -// This test ensures SourceStream.pipe(DestStream) returns DestStream - -var common = require('../common'); -var Stream = require('stream').Stream; -var assert = require('assert'); -var util = require('util'); - -var sourceStream = new Stream(); -var destStream = new Stream(); -var result = sourceStream.pipe(destStream); - -assert.strictEqual(result, destStream); - diff --git a/test/simple/test-pipe-stream.js b/test/simple/test-pipe-stream.js deleted file mode 100644 index b2b2a5518..000000000 --- a/test/simple/test-pipe-stream.js +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -function test(clazz, cb) { - var have_ping = false; - var have_pong = false; - - function check() { - assert.ok(have_ping); - assert.ok(have_pong); - } - - function ping() { - var conn = new clazz(); - - conn.on('error', function(err) { - throw err; - }); - - conn.connect(common.PIPE, function() { - conn.write('PING', 'utf-8'); - }); - - conn.on('data', function(data) { - assert.equal(data.toString(), 'PONG'); - have_pong = true; - conn.destroy(); - }); - } - - function pong(conn) { - conn.on('error', function(err) { - throw err; - }); - - conn.on('data', function(data) { - assert.equal(data.toString(), 'PING'); - have_ping = true; - conn.write('PONG', 'utf-8'); - }); - - conn.on('close', function() { - server.close(); - }); - } - - var timeout = setTimeout(function() { - server.close(); - }, 2000); - - var server = net.Server(); - server.listen(common.PIPE, ping); - server.on('connection', pong); - server.on('close', function() { - clearTimeout(timeout); - check(); - cb && cb(); - }); -} - -test(net.Stream, function() { - test(net.Socket); -}); - diff --git a/test/simple/test-pipe-unref.js b/test/simple/test-pipe-unref.js deleted file mode 100644 index 9f715a9d1..000000000 --- a/test/simple/test-pipe-unref.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var net = require('net'); -var closed = false; - -var s = net.Server(); -s.listen(common.PIPE); -s.unref(); - -setTimeout(function() { - closed = true; - s.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); -}); diff --git a/test/simple/test-pipe.js b/test/simple/test-pipe.js deleted file mode 100644 index 9f1dae885..000000000 --- a/test/simple/test-pipe.js +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); -var net = require('net'); - -var webPort = common.PORT; -var tcpPort = webPort + 1; - -var listenCount = 0; -var gotThanks = false; -var tcpLengthSeen = 0; -var bufferSize = 5 * 1024 * 1024; - - -/* - * 5MB of random buffer. - */ -var buffer = Buffer(bufferSize); -for (var i = 0; i < buffer.length; i++) { - buffer[i] = parseInt(Math.random() * 10000) % 256; -} - - -var web = http.Server(function(req, res) { - web.close(); - - console.log(req.headers); - - var socket = net.Stream(); - socket.connect(tcpPort); - - socket.on('connect', function() { - console.log('socket connected'); - }); - - req.pipe(socket); - - req.on('end', function() { - res.writeHead(200); - res.write('thanks'); - res.end(); - console.log('response with \'thanks\''); - }); - - req.connection.on('error', function(e) { - console.log('http server-side error: ' + e.message); - process.exit(1); - }); -}); -web.listen(webPort, startClient); - - - -var tcp = net.Server(function(s) { - tcp.close(); - - console.log('tcp server connection'); - - var i = 0; - - s.on('data', function(d) { - process.stdout.write('.'); - tcpLengthSeen += d.length; - for (var j = 0; j < d.length; j++) { - assert.equal(buffer[i], d[j]); - i++; - } - }); - - s.on('end', function() { - console.log('tcp socket disconnect'); - s.end(); - }); - - s.on('error', function(e) { - console.log('tcp server-side error: ' + e.message); - process.exit(1); - }); -}); -tcp.listen(tcpPort, startClient); - - -function startClient() { - listenCount++; - if (listenCount < 2) return; - - console.log('Making request'); - - var req = http.request({ - port: common.PORT, - method: 'GET', - path: '/', - headers: { 'content-length': buffer.length } - }, function(res) { - console.log('Got response'); - res.setEncoding('utf8'); - res.on('data', function(string) { - assert.equal('thanks', string); - gotThanks = true; - }); - }); - req.write(buffer); - req.end(); - console.error('ended request', req); -} - -process.on('exit', function() { - assert.ok(gotThanks); - assert.equal(bufferSize, tcpLengthSeen); -}); - diff --git a/test/simple/test-process-active-wraps.js b/test/simple/test-process-active-wraps.js deleted file mode 100644 index 63fc218de..000000000 --- a/test/simple/test-process-active-wraps.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var net = require('net'); - -function expect(activeHandles, activeRequests) { - assert.equal(process._getActiveHandles().length, activeHandles); - assert.equal(process._getActiveRequests().length, activeRequests); -} - -var handles = []; - -(function() { - expect(0, 0); - var server = net.createServer().listen(common.PORT); - expect(1, 0); - server.close(); - expect(1, 0); // server handle doesn't shut down until next tick - handles.push(server); -})(); - -(function() { - expect(1, 0); - var conn = net.createConnection(common.PORT); - conn.on('error', function() { /* ignore */ }); - expect(2, 1); - conn.destroy(); - expect(2, 1); // client handle doesn't shut down until next tick - handles.push(conn); -})(); - -(function() { - var n = 0; - handles.forEach(function(handle) { - handle.once('close', onclose); - }); - function onclose() { - if (++n === handles.length) setImmediate(expect, 0, 0); - } -})(); diff --git a/test/simple/test-process-argv-0.js b/test/simple/test-process-argv-0.js deleted file mode 100644 index 0c38f6ac7..000000000 --- a/test/simple/test-process-argv-0.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -var util = require('util'); -var path = require('path'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var common = require('../common'); - -console.error('argv=%j', process.argv); -console.error('exec=%j', process.execPath); - -if (process.argv[2] !== "child") { - var child = spawn('./node', [__filename, "child"], { - cwd: path.dirname(process.execPath) - }); - - var childArgv0 = ''; - var childErr = ''; - child.stdout.on('data', function(chunk) { - childArgv0 += chunk; - }); - child.stderr.on('data', function(chunk) { - childErr += chunk; - }); - child.on('exit', function () { - console.error('CHILD: %s', childErr.trim().split('\n').join('\nCHILD: ')); - if (process.platform === 'win32') { - // On Windows argv[0] is not expanded into full path - assert.equal(childArgv0, './node'); - } else { - assert.equal(childArgv0, process.execPath); - } - }); -} -else { - process.stdout.write(process.argv[0]); -} diff --git a/test/simple/test-process-before-exit.js b/test/simple/test-process-before-exit.js deleted file mode 100644 index 261ac253c..000000000 --- a/test/simple/test-process-before-exit.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); - -var N = 5; -var n = 0; - -function f() { - if (++n < N) setTimeout(f, 5); -} -process.on('beforeExit', f); -process.on('exit', function() { - assert.equal(n, N + 1); // The sixth time we let it through. -}); diff --git a/test/simple/test-process-binding.js b/test/simple/test-process-binding.js deleted file mode 100644 index c803a8083..000000000 --- a/test/simple/test-process-binding.js +++ /dev/null @@ -1,16 +0,0 @@ -var assert = require('assert'); - -assert.throws( - function() { - process.binding('test'); - }, - /No such module: test/ -); - -assert.doesNotThrow(function () { - process.binding('buffer'); -}, function(err) { - if ( (err instanceof Error) ) { - return true; - } -}, "unexpected error"); diff --git a/test/simple/test-process-config.js b/test/simple/test-process-config.js deleted file mode 100644 index b3236cd5e..000000000 --- a/test/simple/test-process-config.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); - -// check for existence -assert(process.hasOwnProperty('config')); - -// ensure that `process.config` is an Object -assert(Object(process.config) === process.config); - -var configPath = path.resolve(__dirname, '..', '..', 'config.gypi'); -var config = fs.readFileSync(configPath, 'utf8'); - -// clean up comment at the first line -config = config.split('\n').slice(1).join('\n').replace(/'/g, '"'); -config = JSON.parse(config, function(key, value) { - if (value === 'true') return true; - if (value === 'false') return false; - return value; -}); - -assert.deepEqual(config, process.config); diff --git a/test/simple/test-process-env.js b/test/simple/test-process-env.js deleted file mode 100644 index 919d0d54e..000000000 --- a/test/simple/test-process-env.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// first things first, set the timezone; see tzset(3) -process.env.TZ = 'Europe/Amsterdam'; - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -/* For the moment we are not going to support setting the timezone via the - * environment variables. The problem is that various V8 platform backends - * deal with timezone in different ways. The windows platform backend caches - * the timezone value while the Linux one hits libc for every query. - -https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-linux.cc#L339-345 -https://github.com/joyent/node/blob/08782931205bc4f6d28102ebc29fd806e8ccdf1f/deps/v8/src/platform-win32.cc#L590-596 - - -// time difference between Greenwich and Amsterdam is +2 hours in the summer -date = new Date('Fri, 10 Sep 1982 03:15:00 GMT'); -assert.equal(3, date.getUTCHours()); -assert.equal(5, date.getHours()); -*/ - - -// changes in environment should be visible to child processes -if (process.argv[2] == 'you-are-the-child') { - // failed assertion results in process exiting with status code 1 - assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); - assert.equal(42, process.env.NODE_PROCESS_ENV); - assert.equal('asdf', process.env.hasOwnProperty); - var hasOwnProperty = Object.prototype.hasOwnProperty; - var has = hasOwnProperty.call(process.env, 'hasOwnProperty'); - assert.equal(true, has); - process.exit(0); -} else { - assert.equal(Object.prototype.hasOwnProperty, process.env.hasOwnProperty); - var has = process.env.hasOwnProperty('hasOwnProperty'); - assert.equal(false, has); - - process.env.hasOwnProperty = 'asdf'; - - process.env.NODE_PROCESS_ENV = 42; - assert.equal(42, process.env.NODE_PROCESS_ENV); - - process.env.NODE_PROCESS_ENV_DELETED = 42; - assert.equal(true, 'NODE_PROCESS_ENV_DELETED' in process.env); - - delete process.env.NODE_PROCESS_ENV_DELETED; - assert.equal(false, 'NODE_PROCESS_ENV_DELETED' in process.env); - - var child = spawn(process.argv[0], [process.argv[1], 'you-are-the-child']); - child.stdout.on('data', function(data) { console.log(data.toString()); }); - child.stderr.on('data', function(data) { console.log(data.toString()); }); - child.on('exit', function(statusCode) { - if (statusCode != 0) { - process.exit(statusCode); // failed assertion in child process - } - }); -} diff --git a/test/simple/test-process-exec-argv.js b/test/simple/test-process-exec-argv.js deleted file mode 100644 index 395753b72..000000000 --- a/test/simple/test-process-exec-argv.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var spawn = require('child_process').spawn; - -if (process.argv[2] === 'child') { - process.stdout.write(JSON.stringify(process.execArgv)); -} else { - var execArgv = ['--harmony_proxies', '--stack-size=256']; - var args = [__filename, 'child', 'arg0']; - var child = spawn(process.execPath, execArgv.concat(args)); - var out = ''; - - child.stdout.on('data', function (chunk) { - out += chunk; - }); - - child.on('exit', function () { - assert.deepEqual(JSON.parse(out), execArgv); - }); -} diff --git a/test/simple/test-process-exit-code.js b/test/simple/test-process-exit-code.js deleted file mode 100644 index 2488175d3..000000000 --- a/test/simple/test-process-exit-code.js +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -switch (process.argv[2]) { - case 'child1': - return child1(); - case 'child2': - return child2(); - case 'child3': - return child3(); - case 'child4': - return child4(); - case 'child5': - return child5(); - case undefined: - return parent(); - default: - throw new Error('wtf'); -} - -function child1() { - process.exitCode = 42; - process.on('exit', function(code) { - assert.equal(code, 42); - }); -} - -function child2() { - process.exitCode = 99; - process.on('exit', function(code) { - assert.equal(code, 42); - }); - process.exit(42); -} - -function child3() { - process.exitCode = 99; - process.on('exit', function(code) { - assert.equal(code, 0); - }); - process.exit(0); -} - -function child4() { - process.exitCode = 99; - process.on('exit', function(code) { - if (code !== 1) { - console.log('wrong code! expected 1 for uncaughtException'); - process.exit(99); - } - }); - throw new Error('ok'); -} - -function child5() { - process.exitCode = 95; - process.on('exit', function(code) { - assert.equal(code, 95); - process.exitCode = 99; - }); -} - -function parent() { - test('child1', 42); - test('child2', 42); - test('child3', 0); - test('child4', 1); - test('child5', 99); -} - -function test(arg, exit) { - var spawn = require('child_process').spawn; - var node = process.execPath; - var f = __filename; - var option = { stdio: [ 0, 1, 'ignore' ] }; - spawn(node, [f, arg], option).on('exit', function(code) { - assert.equal(code, exit, 'wrong exit for ' + - arg + '\nexpected:' + exit + - ' but got:' + code); - console.log('ok - %s exited with %d', arg, exit); - }); -} diff --git a/test/simple/test-process-exit-from-before-exit.js b/test/simple/test-process-exit-from-before-exit.js deleted file mode 100644 index 4818a6c19..000000000 --- a/test/simple/test-process-exit-from-before-exit.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); - -process.on('beforeExit', common.mustCall(function() { - setTimeout(assert.fail, 5); - process.exit(0); // Should execute immediately even if we schedule new work. - assert.fail(); -})); diff --git a/test/simple/test-process-exit-recursive.js b/test/simple/test-process-exit-recursive.js deleted file mode 100644 index ba5b5dc5b..000000000 --- a/test/simple/test-process-exit-recursive.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); - -// recursively calling .exit() should not overflow the call stack -var nexits = 0; - -process.on('exit', function(code) { - assert.equal(nexits++, 0); - assert.equal(code, 1); - - // now override the exit code of 1 with 0 so that the test passes - process.exit(0); -}); - -process.exit(1); diff --git a/test/simple/test-process-exit.js b/test/simple/test-process-exit.js deleted file mode 100644 index 365d5f109..000000000 --- a/test/simple/test-process-exit.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// calling .exit() from within "exit" should not overflow the call stack -var nexits = 0; - -process.on('exit', function(code) { - assert.equal(nexits++, 0); - assert.equal(code, 0); - process.exit(); -}); - -// "exit" should be emitted unprovoked diff --git a/test/simple/test-process-getgroups.js b/test/simple/test-process-getgroups.js deleted file mode 100644 index 16d017b3c..000000000 --- a/test/simple/test-process-getgroups.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; - -if (process.platform === 'darwin') { - console.log('Skipping. Output of `id -G` is unreliable on Darwin.'); - return; -} - -if (typeof process.getgroups === 'function') { - var groups = process.getgroups(); - assert(Array.isArray(groups)); - assert(groups.length > 0); - exec('id -G', function(err, stdout) { - if (err) throw err; - var real_groups = stdout.match(/\d+/g).map(Number); - assert.equal(groups.length, real_groups.length); - check(groups, real_groups); - check(real_groups, groups); - }); -} - -function check(a, b) { - for (var i = 0; i < a.length; ++i) assert(b.indexOf(a[i]) !== -1); -} diff --git a/test/simple/test-process-hrtime.js b/test/simple/test-process-hrtime.js deleted file mode 100644 index d8ffcafa9..000000000 --- a/test/simple/test-process-hrtime.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// the default behavior, return an Array "tuple" of numbers -var tuple = process.hrtime(); - -// validate the default behavior -validateTuple(tuple); - -// validate that passing an existing tuple returns another valid tuple -validateTuple(process.hrtime(tuple)); - -// test that only an Array may be passed to process.hrtime() -assert.throws(function() { - process.hrtime(1); -}); - -function validateTuple(tuple) { - assert(Array.isArray(tuple)); - assert.equal(2, tuple.length); - tuple.forEach(function (v) { - assert.equal('number', typeof v); - assert(isFinite(v)); - }); -} diff --git a/test/simple/test-process-kill-null.js b/test/simple/test-process-kill-null.js deleted file mode 100644 index 520210ef1..000000000 --- a/test/simple/test-process-kill-null.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -var cat = spawn('cat'); -var called; - -assert.ok(process.kill(cat.pid, 0)); - -cat.on('exit', function() { - assert.throws(function() { - process.kill(cat.pid, 0); - }, Error); -}); - -cat.stdout.on('data', function() { - called = true; - process.kill(cat.pid, 'SIGKILL'); -}); - -// EPIPE when null sig fails -cat.stdin.write('test'); - -process.on('exit', function() { - assert.ok(called); -}); diff --git a/test/simple/test-process-kill-pid.js b/test/simple/test-process-kill-pid.js deleted file mode 100644 index 6e4e7d83a..000000000 --- a/test/simple/test-process-kill-pid.js +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); - -// test variants of pid -// -// null: TypeError -// undefined: TypeError -// -// 'SIGTERM': TypeError -// -// String(process.pid): TypeError -// -// Nan, Infinity, -Infinity: TypeError -// -// 0, String(0): our group process -// -// process.pid, String(process.pid): ourself - -assert.throws(function() { process.kill('SIGTERM'); }, TypeError); -assert.throws(function() { process.kill(null); }, TypeError); -assert.throws(function() { process.kill(undefined); }, TypeError); -assert.throws(function() { process.kill(+'not a number'); }, TypeError); -assert.throws(function() { process.kill(1/0); }, TypeError); -assert.throws(function() { process.kill(-1/0); }, TypeError); - -// Test kill argument processing in valid cases. -// -// Monkey patch _kill so that we don't actually send any signals, particularly -// that we don't kill our process group, or try to actually send ANY signals on -// windows, which doesn't support them. -function kill(tryPid, trySig, expectPid, expectSig) { - var getPid; - var getSig; - var origKill = process._kill; - process._kill = function(pid, sig) { - getPid = pid; - getSig = sig; - - // un-monkey patch process._kill - process._kill = origKill; - }; - - process.kill(tryPid, trySig); - - assert.equal(getPid, expectPid); - assert.equal(getSig, expectSig); -} - -// Note that SIGHUP and SIGTERM map to 1 and 15 respectively, even on Windows -// (for Windows, libuv maps 1 and 15 to the correct behaviour). - -kill(0, 'SIGHUP', 0, 1); -kill(0, undefined, 0, 15); -kill('0', 'SIGHUP', 0, 1); -kill('0', undefined, 0, 15); - -// negative numbers are meaningful on unix -kill(-1, 'SIGHUP', -1, 1); -kill(-1, undefined, -1, 15); -kill('-1', 'SIGHUP', -1, 1); -kill('-1', undefined, -1, 15); - -kill(process.pid, 'SIGHUP', process.pid, 1); -kill(process.pid, undefined, process.pid, 15); -kill(String(process.pid), 'SIGHUP', process.pid, 1); -kill(String(process.pid), undefined, process.pid, 15); diff --git a/test/simple/test-process-next-tick.js b/test/simple/test-process-next-tick.js deleted file mode 100644 index 0322a033e..000000000 --- a/test/simple/test-process-next-tick.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var N = 2; -var tickCount = 0; -var exceptionCount = 0; - -function cb() { - ++tickCount; - throw new Error(); -} - -for (var i = 0; i < N; ++i) { - process.nextTick(cb); -} - -process.on('uncaughtException', function() { - ++exceptionCount; -}); - -process.on('exit', function() { - process.removeAllListeners('uncaughtException'); - assert.equal(tickCount, N); - assert.equal(exceptionCount, N); -}); diff --git a/test/simple/test-process-raw-debug.js b/test/simple/test-process-raw-debug.js deleted file mode 100644 index 3c14c9eb5..000000000 --- a/test/simple/test-process-raw-debug.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var os = require('os'); - -switch (process.argv[2]) { - case 'child': - return child(); - case undefined: - return parent(); - default: - throw new Error('wtf? ' + process.argv[2]); -} - -function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); - - var output = ''; - - child.stderr.on('data', function(c) { - output += c; - }); - - child.stderr.setEncoding('utf8'); - - child.stderr.on('end', function() { - assert.equal(output, 'I can still debug!' + os.EOL); - console.log('ok - got expected message'); - }); - - child.on('exit', function(c) { - assert(!c); - console.log('ok - child exited nicely'); - }); -} - -function child() { - // even when all hope is lost... - - process.nextTick = function() { - throw new Error('No ticking!'); - }; - - var stderr = process.stderr; - stderr.write = function() { - throw new Error('No writing to stderr!'); - }; - - process._rawDebug('I can still %s!', 'debug'); -} diff --git a/test/simple/test-process-wrap.js b/test/simple/test-process-wrap.js deleted file mode 100644 index 892b028e3..000000000 --- a/test/simple/test-process-wrap.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var Process = process.binding('process_wrap').Process; -var Pipe = process.binding('pipe_wrap').Pipe; -var pipe = new Pipe(); -var p = new Process(); - -var processExited = false; -var gotPipeEOF = false; -var gotPipeData = false; - -p.onexit = function(exitCode, signal) { - console.log('exit'); - p.close(); - pipe.readStart(); - - assert.equal(0, exitCode); - assert.equal(0, signal); - - processExited = true; -}; - -pipe.onread = function(err, b, off, len) { - assert.ok(processExited); - if (b) { - gotPipeData = true; - console.log('read %d', len); - } else { - gotPipeEOF = true; - pipe.close(); - } -}; - -p.spawn({ - file: process.execPath, - args: [process.execPath, '-v'], - stdio: [ - { type: 'ignore' }, - { type: 'pipe', handle: pipe }, - { type: 'ignore' } - ] -}); - -// 'this' safety -// https://github.com/joyent/node/issues/6690 -assert.throws(function() { - var notp = { spawn: p.spawn }; - notp.spawn({ - file: process.execPath, - args: [process.execPath, '-v'], - stdio: [ - { type: 'ignore' }, - { type: 'pipe', handle: pipe }, - { type: 'ignore' } - ] - }); -}, TypeError); - -process.on('exit', function() { - assert.ok(processExited); - assert.ok(gotPipeEOF); - assert.ok(gotPipeData); -}); diff --git a/test/simple/test-pump-file2tcp-noexist.js b/test/simple/test-pump-file2tcp-noexist.js deleted file mode 100644 index 8017db73f..000000000 --- a/test/simple/test-pump-file2tcp-noexist.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var fs = require('fs'); -var util = require('util'); -var path = require('path'); -var fn = path.join(common.fixturesDir, 'does_not_exist.txt'); - -var got_error = false; -var conn_closed = false; - -var server = net.createServer(function(stream) { - common.error('pump!'); - util.pump(fs.createReadStream(fn), stream, function(err) { - common.error('util.pump\'s callback fired'); - if (err) { - got_error = true; - } else { - common.debug('util.pump\'s callback fired with no error'); - common.debug('this shouldn\'t happen as the file doesn\'t exist...'); - assert.equal(true, false); - } - server.close(); - }); -}); - -server.listen(common.PORT, function() { - var conn = net.createConnection(common.PORT); - conn.setEncoding('utf8'); - conn.on('data', function(chunk) { - common.error('recv data! nchars = ' + chunk.length); - buffer += chunk; - }); - - conn.on('end', function() { - conn.end(); - }); - - conn.on('close', function() { - common.error('client connection close'); - conn_closed = true; - }); -}); - -var buffer = ''; - -process.on('exit', function() { - assert.equal(true, got_error); - assert.equal(true, conn_closed); - console.log('exiting'); -}); diff --git a/test/simple/test-pump-file2tcp.js b/test/simple/test-pump-file2tcp.js deleted file mode 100644 index 60c0fdd7f..000000000 --- a/test/simple/test-pump-file2tcp.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var fs = require('fs'); -var util = require('util'); -var path = require('path'); -var fn = path.join(common.fixturesDir, 'elipses.txt'); - -var expected = fs.readFileSync(fn, 'utf8'); - -var server = net.createServer(function(stream) { - common.error('pump!'); - util.pump(fs.createReadStream(fn), stream, function() { - common.error('server stream close'); - common.error('server close'); - server.close(); - }); -}); - -server.listen(common.PORT, function() { - var conn = net.createConnection(common.PORT); - conn.setEncoding('utf8'); - conn.on('data', function(chunk) { - common.error('recv data! nchars = ' + chunk.length); - buffer += chunk; - }); - - conn.on('end', function() { - conn.end(); - }); - conn.on('close', function() { - common.error('client connection close'); - }); -}); - -var buffer = ''; -var count = 0; - -server.on('listening', function() { -}); - -process.on('exit', function() { - assert.equal(expected, buffer); -}); diff --git a/test/simple/test-punycode.js b/test/simple/test-punycode.js deleted file mode 100644 index fa6a9c0ec..000000000 --- a/test/simple/test-punycode.js +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Copyright (C) 2011 by Ben Noordhuis -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -var common = require('../common'); -var punycode = require('punycode'); -var assert = require('assert'); - -assert.equal(punycode.encode('ü'), 'tda'); -assert.equal(punycode.encode('Goethe'), 'Goethe-'); -assert.equal(punycode.encode('Bücher'), 'Bcher-kva'); -assert.equal(punycode.encode( - 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'), - 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'); -assert.equal(punycode.encode('日本語'), 'wgv71a119e'); - -assert.equal(punycode.decode('tda'), 'ü'); -assert.equal(punycode.decode('Goethe-'), 'Goethe'); -assert.equal(punycode.decode('Bcher-kva'), 'Bücher'); -assert.equal(punycode.decode( - 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), - 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); -assert.equal(punycode.decode('wgv71a119e'), '日本語'); - -// http://tools.ietf.org/html/rfc3492#section-7.1 -var tests = { - // (A) Arabic (Egyptian) - 'egbpdaj6bu4bxfgehfvwxn': - '\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648' + - '\u0634\u0639\u0631\u0628\u064A\u061F', - - // (B) Chinese (simplified) - 'ihqwcrb4cv8a8dqg056pqjye': - '\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587', - - // (C) Chinese (traditional) - 'ihqwctvzc91f659drss3x8bo0yb': - '\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587', - - // (D) Czech: Proprostnemluvesky - 'Proprostnemluvesky-uyb24dma41a': - '\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074\u011B\u006E' + - '\u0065\u006D\u006C\u0075\u0076\u00ED\u010D\u0065\u0073\u006B\u0079', - - // (E) Hebrew - '4dbcagdahymbxekheh6e0a7fei0b': - '\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8\u05DC\u05D0' + - '\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2\u05D1\u05E8\u05D9\u05EA', - - // (F) Hindi (Devanagari) - 'i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd': - '\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D\u0926\u0940' + - '\u0915\u094D\u092F\u094B\u0902\u0928\u0939\u0940\u0902\u092C\u094B' + - '\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902', - - // (G) Japanese (kanji and hiragana) - 'n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa': - '\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092\u8A71\u3057' + - '\u3066\u304F\u308C\u306A\u3044\u306E\u304B', - - // (H) Korean (Hangul syllables) - '989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c': - '\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774\uD55C\uAD6D' + - '\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74\uC5BC\uB9C8\uB098\uC88B' + - '\uC744\uAE4C', - - // (I) Russian (Cyrillic) - /* XXX disabled, fails - possibly a bug in the RFC - 'b1abfaaepdrnnbgefbaDotcwatmq2g4l': - '\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438' + - '\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E' + - '\u0440\u0443\u0441\u0441\u043A\u0438', - */ - - // (J) Spanish: PorqunopuedensimplementehablarenEspaol - 'PorqunopuedensimplementehablarenEspaol-fmd56a': - '\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070\u0075\u0065' + - '\u0064\u0065\u006E\u0073\u0069\u006D\u0070\u006C\u0065\u006D\u0065' + - '\u006E\u0074\u0065\u0068\u0061\u0062\u006C\u0061\u0072\u0065\u006E' + - '\u0045\u0073\u0070\u0061\u00F1\u006F\u006C', - - // (K) Vietnamese: Tisaohkhngth - // chnitingVit - 'TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g': - '\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B\u0068\u00F4' + - '\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068\u1EC9\u006E\u00F3\u0069' + - '\u0074\u0069\u1EBF\u006E\u0067\u0056\u0069\u1EC7\u0074', - - // (L) 3B - '3B-ww4c5e180e575a65lsy2b': - '\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F', - - // (M) -with-SUPER-MONKEYS - '-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n': - '\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074\u0068\u002D' + - '\u0053\u0055\u0050\u0045\u0052\u002D\u004D\u004F\u004E\u004B\u0045' + - '\u0059\u0053', - - // (N) Hello-Another-Way- - 'Hello-Another-Way--fc4qua05auwb3674vfr0b': - '\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F\u0074\u0068' + - '\u0065\u0072\u002D\u0057\u0061\u0079\u002D\u305D\u308C\u305E\u308C' + - '\u306E\u5834\u6240', - - // (O) 2 - '2-u9tlzr9756bt3uc0v': - '\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032', - - // (P) MajiKoi5 - 'MajiKoi5-783gue6qz075azm5e': - '\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059\u308B\u0035' + - '\u79D2\u524D', - - // (Q) de - 'de-jg4avhby1noc0d': - '\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0', - - // (R) - 'd9juau41awczczp': - '\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067', - - // (S) -> $1.00 <- - '-> $1.00 <--': - '\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020\u003C\u002D' -}; - -var errors = 0; - -for (var encoded in tests) { - var decoded = tests[encoded]; - try { - assert.equal(punycode.encode(decoded), encoded); - } catch (e) { - console.error('FAIL: expected %j, got %j', e.expected, e.actual); - errors++; - } - try { - assert.equal(punycode.decode(encoded), decoded); - } catch (e) { - console.error('FAIL: expected %j, got %j', e.expected, e.actual); - errors++; - } -} - -// BMP code point -assert.equal(punycode.ucs2.encode([0x61]), 'a'); -// supplementary code point (surrogate pair) -assert.equal(punycode.ucs2.encode([0x1D306]), '\uD834\uDF06'); -// high surrogate -assert.equal(punycode.ucs2.encode([0xD800]), '\uD800'); -// high surrogate followed by non-surrogates -assert.equal(punycode.ucs2.encode([0xD800, 0x61, 0x62]), '\uD800ab'); -// low surrogate -assert.equal(punycode.ucs2.encode([0xDC00]), '\uDC00'); -// low surrogate followed by non-surrogates -assert.equal(punycode.ucs2.encode([0xDC00, 0x61, 0x62]), '\uDC00ab'); - -assert.equal(errors, 0); diff --git a/test/simple/test-querystring.js b/test/simple/test-querystring.js deleted file mode 100644 index 6bb3fe7c6..000000000 --- a/test/simple/test-querystring.js +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// test using assert -var qs = require('querystring'); - -// folding block, commented to pass gjslint -// {{{ -// [ wonkyQS, canonicalQS, obj ] -var qsTestCases = [ - ['foo=918854443121279438895193', - 'foo=918854443121279438895193', - {'foo': '918854443121279438895193'}], - ['foo=bar', 'foo=bar', {'foo': 'bar'}], - ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], - ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], - ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', - 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', - {'my weird field': 'q1!2"\'w$5&7/z8)?' }], - ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], - ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], - ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', - 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', - { 'str': 'foo', - 'arr': ['1', '2', '3'], - 'somenull': '', - 'undef': ''}], - [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], - ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], - ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], - // See: https://github.com/joyent/node/issues/1707 - ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', - 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', - { hasOwnProperty: 'x', - toString: 'foo', - valueOf: 'bar', - __defineGetter__: 'baz' }], - // See: https://github.com/joyent/node/issues/3058 - ['foo&bar=baz', 'foo=&bar=baz', { foo: '', bar: 'baz' }], - [null, '', {}], - [undefined, '', {}] -]; - -// [ wonkyQS, canonicalQS, obj ] -var qsColonTestCases = [ - ['foo:bar', 'foo:bar', {'foo': 'bar'}], - ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], - ['foo:1&bar:2;baz:quux', - 'foo:1%26bar%3A2;baz:quux', - {'foo': '1&bar:2', 'baz': 'quux'}], - ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], - ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] -]; - -// [wonkyObj, qs, canonicalObj] -var extendedFunction = function() {}; -extendedFunction.prototype = {a: 'b'}; -var qsWeirdObjects = [ - [{regexp: /./g}, 'regexp=', {'regexp': ''}], - [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], - [{fn: function() {}}, 'fn=', {'fn': ''}], - [{fn: new Function('')}, 'fn=', {'fn': ''}], - [{math: Math}, 'math=', {'math': ''}], - [{e: extendedFunction}, 'e=', {'e': ''}], - [{d: new Date()}, 'd=', {'d': ''}], - [{d: Date}, 'd=', {'d': ''}], - [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], - [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], - [{n: null}, 'n=', {'n': ''}], - [{nan: NaN}, 'nan=', {'nan': ''}], - [{inf: Infinity}, 'inf=', {'inf': ''}], - [{a: [], b: []}, '', {}] -]; -// }}} - -var vm = require('vm'); -var foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); - -var qsNoMungeTestCases = [ - ['', {}], - ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], - ['foo=bar&foo=baz', foreignObject], - ['blah=burp', {'blah': 'burp'}], - ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], - ['frappucino=muffin&goat%5B%5D=scone&pond=moose', - {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], - ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] -]; - -assert.strictEqual('918854443121279438895193', - qs.parse('id=918854443121279438895193').id); - -// test that the canonical qs is parsed properly. -qsTestCases.forEach(function(testCase) { - assert.deepEqual(testCase[2], qs.parse(testCase[0])); -}); - -// test that the colon test cases can do the same -qsColonTestCases.forEach(function(testCase) { - assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':')); -}); - -// test the weird objects, that they get parsed properly -qsWeirdObjects.forEach(function(testCase) { - assert.deepEqual(testCase[2], qs.parse(testCase[1])); -}); - -qsNoMungeTestCases.forEach(function(testCase) { - assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=')); -}); - -// test the nested qs-in-qs case -(function() { - var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); - f.q = qs.parse(f.q); - assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); -})(); - -// nested in colon -(function() { - var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); - f.q = qs.parse(f.q, ';', ':'); - assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }); -})(); - -// now test stringifying - -// basic -qsTestCases.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[2])); -}); - -qsColonTestCases.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':')); -}); - -qsWeirdObjects.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[0])); -}); - -// nested -var f = qs.stringify({ - a: 'b', - q: qs.stringify({ - x: 'y', - y: 'z' - }) -}); -assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz'); - -assert.doesNotThrow(function() { - qs.parse(undefined); -}); - -// nested in colon -var f = qs.stringify({ - a: 'b', - q: qs.stringify({ - x: 'y', - y: 'z' - }, ';', ':') -}, ';', ':'); -assert.equal(f, 'a:b;q:x%3Ay%3By%3Az'); - - -assert.deepEqual({}, qs.parse()); - - -// Test limiting -assert.equal( - Object.keys(qs.parse('a=1&b=1&c=1', null, null, { maxKeys: 1 })).length, - 1); - -// Test removing limit -function testUnlimitedKeys() { - var query = {}, - url; - - for (var i = 0; i < 2000; i++) query[i] = i; - - url = qs.stringify(query); - - assert.equal( - Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length, - 2000); -} -testUnlimitedKeys(); - - -var b = qs.unescapeBuffer('%d3%f2Ug%1f6v%24%5e%98%cb' + - '%0d%ac%a2%2f%9d%eb%d8%a2%e6'); -// -assert.equal(0xd3, b[0]); -assert.equal(0xf2, b[1]); -assert.equal(0x55, b[2]); -assert.equal(0x67, b[3]); -assert.equal(0x1f, b[4]); -assert.equal(0x36, b[5]); -assert.equal(0x76, b[6]); -assert.equal(0x24, b[7]); -assert.equal(0x5e, b[8]); -assert.equal(0x98, b[9]); -assert.equal(0xcb, b[10]); -assert.equal(0x0d, b[11]); -assert.equal(0xac, b[12]); -assert.equal(0xa2, b[13]); -assert.equal(0x2f, b[14]); -assert.equal(0x9d, b[15]); -assert.equal(0xeb, b[16]); -assert.equal(0xd8, b[17]); -assert.equal(0xa2, b[18]); -assert.equal(0xe6, b[19]); - - -// Test custom decode -function demoDecode(str) { - return str + str; -} -assert.deepEqual( - qs.parse('a=a&b=b&c=c', null, null, { decodeURIComponent: demoDecode }), - { aa: 'aa', bb: 'bb', cc: 'cc' }); - - -// Test custom encode -function demoEncode(str) { - return str[0]; -} -var obj = { aa: 'aa', bb: 'bb', cc: 'cc' }; -assert.equal( - qs.stringify(obj, null, null, { encodeURIComponent: demoEncode }), - 'a=a&b=b&c=c'); - -// test overriding .unescape -var prevUnescape = qs.unescape; -qs.unescape = function (str) { - return str.replace(/o/g, '_'); -}; -assert.deepEqual(qs.parse('foo=bor'), {f__: 'b_r'}); -qs.unescape = prevUnescape; diff --git a/test/simple/test-readdir.js b/test/simple/test-readdir.js deleted file mode 100644 index 24997241f..000000000 --- a/test/simple/test-readdir.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var got_error = false, - readdirDir = path.join(common.fixturesDir, 'readdir'); - -var files = ['are', - 'dir', - 'empty', - 'files', - 'for', - 'just', - 'testing.js', - 'these']; - - -console.log('readdirSync ' + readdirDir); -var f = fs.readdirSync(readdirDir); -console.dir(f); -assert.deepEqual(files, f.sort()); - - -console.log('readdir ' + readdirDir); -fs.readdir(readdirDir, function(err, f) { - if (err) { - console.log('error'); - got_error = true; - } else { - console.dir(f); - assert.deepEqual(files, f.sort()); - } -}); - -process.on('exit', function() { - assert.equal(false, got_error); - console.log('exit'); -}); - - -// readdir() on file should throw ENOTDIR -// https://github.com/joyent/node/issues/1869 -(function() { - var has_caught = false; - - try { - fs.readdirSync(__filename); - } - catch (e) { - has_caught = true; - assert.equal(e.code, 'ENOTDIR'); - } - - assert(has_caught); -})(); - - -(function() { - var readdir_cb_called = false; - - fs.readdir(__filename, function(e) { - readdir_cb_called = true; - assert.equal(e.code, 'ENOTDIR'); - }); - - process.on('exit', function() { - assert(readdir_cb_called); - }); -})(); diff --git a/test/simple/test-readdouble.js b/test/simple/test-readdouble.js deleted file mode 100644 index 6749e5b20..000000000 --- a/test/simple/test-readdouble.js +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * Tests to verify we're reading in doubles correctly - */ -var common = require('../common'); -var ASSERT = require('assert'); - -/* - * Test (64 bit) double - */ -function test(clazz) { - var buffer = new clazz(8); - - buffer[0] = 0x55; - buffer[1] = 0x55; - buffer[2] = 0x55; - buffer[3] = 0x55; - buffer[4] = 0x55; - buffer[5] = 0x55; - buffer[6] = 0xd5; - buffer[7] = 0x3f; - ASSERT.equal(1.1945305291680097e+103, buffer.readDoubleBE(0)); - ASSERT.equal(0.3333333333333333, buffer.readDoubleLE(0)); - - buffer[0] = 1; - buffer[1] = 0; - buffer[2] = 0; - buffer[3] = 0; - buffer[4] = 0; - buffer[5] = 0; - buffer[6] = 0xf0; - buffer[7] = 0x3f; - ASSERT.equal(7.291122019655968e-304, buffer.readDoubleBE(0)); - ASSERT.equal(1.0000000000000002, buffer.readDoubleLE(0)); - - buffer[0] = 2; - ASSERT.equal(4.778309726801735e-299, buffer.readDoubleBE(0)); - ASSERT.equal(1.0000000000000004, buffer.readDoubleLE(0)); - - buffer[0] = 1; - buffer[6] = 0; - buffer[7] = 0; - ASSERT.equal(7.291122019556398e-304, buffer.readDoubleBE(0)); - ASSERT.equal(5e-324, buffer.readDoubleLE(0)); - - buffer[0] = 0xff; - buffer[1] = 0xff; - buffer[2] = 0xff; - buffer[3] = 0xff; - buffer[4] = 0xff; - buffer[5] = 0xff; - buffer[6] = 0x0f; - buffer[7] = 0x00; - ASSERT.ok(isNaN(buffer.readDoubleBE(0))); - ASSERT.equal(2.225073858507201e-308, buffer.readDoubleLE(0)); - - buffer[6] = 0xef; - buffer[7] = 0x7f; - ASSERT.ok(isNaN(buffer.readDoubleBE(0))); - ASSERT.equal(1.7976931348623157e+308, buffer.readDoubleLE(0)); - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0; - buffer[3] = 0; - buffer[4] = 0; - buffer[5] = 0; - buffer[6] = 0xf0; - buffer[7] = 0x3f; - ASSERT.equal(3.03865e-319, buffer.readDoubleBE(0)); - ASSERT.equal(1, buffer.readDoubleLE(0)); - - buffer[6] = 0; - buffer[7] = 0x40; - ASSERT.equal(3.16e-322, buffer.readDoubleBE(0)); - ASSERT.equal(2, buffer.readDoubleLE(0)); - - buffer[7] = 0xc0; - ASSERT.equal(9.5e-322, buffer.readDoubleBE(0)); - ASSERT.equal(-2, buffer.readDoubleLE(0)); - - buffer[6] = 0x10; - buffer[7] = 0; - ASSERT.equal(2.0237e-320, buffer.readDoubleBE(0)); - ASSERT.equal(2.2250738585072014e-308, buffer.readDoubleLE(0)); - - buffer[6] = 0; - ASSERT.equal(0, buffer.readDoubleBE(0)); - ASSERT.equal(0, buffer.readDoubleLE(0)); - ASSERT.equal(false, 1 / buffer.readDoubleLE(0) < 0); - - buffer[7] = 0x80; - ASSERT.equal(6.3e-322, buffer.readDoubleBE(0)); - ASSERT.equal(0, buffer.readDoubleLE(0)); - ASSERT.equal(true, 1 / buffer.readDoubleLE(0) < 0); - - buffer[6] = 0xf0; - buffer[7] = 0x7f; - ASSERT.equal(3.0418e-319, buffer.readDoubleBE(0)); - ASSERT.equal(Infinity, buffer.readDoubleLE(0)); - - buffer[6] = 0xf0; - buffer[7] = 0xff; - ASSERT.equal(3.04814e-319, buffer.readDoubleBE(0)); - ASSERT.equal(-Infinity, buffer.readDoubleLE(0)); -} - - -test(Buffer); diff --git a/test/simple/test-readfloat.js b/test/simple/test-readfloat.js deleted file mode 100644 index 586b992c5..000000000 --- a/test/simple/test-readfloat.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * Tests to verify we're reading in floats correctly - */ -var common = require('../common'); -var ASSERT = require('assert'); - -/* - * Test (32 bit) float - */ -function test(clazz) { - var buffer = new clazz(4); - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0x80; - buffer[3] = 0x3f; - ASSERT.equal(4.600602988224807e-41, buffer.readFloatBE(0)); - ASSERT.equal(1, buffer.readFloatLE(0)); - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0; - buffer[3] = 0xc0; - ASSERT.equal(2.6904930515036488e-43, buffer.readFloatBE(0)); - ASSERT.equal(-2, buffer.readFloatLE(0)); - - buffer[0] = 0xff; - buffer[1] = 0xff; - buffer[2] = 0x7f; - buffer[3] = 0x7f; - ASSERT.ok(isNaN(buffer.readFloatBE(0))); - ASSERT.equal(3.4028234663852886e+38, buffer.readFloatLE(0)); - - buffer[0] = 0xab; - buffer[1] = 0xaa; - buffer[2] = 0xaa; - buffer[3] = 0x3e; - ASSERT.equal(-1.2126478207002966e-12, buffer.readFloatBE(0)); - ASSERT.equal(0.3333333432674408, buffer.readFloatLE(0)); - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0; - buffer[3] = 0; - ASSERT.equal(0, buffer.readFloatBE(0)); - ASSERT.equal(0, buffer.readFloatLE(0)); - ASSERT.equal(false, 1 / buffer.readFloatLE(0) < 0); - - buffer[3] = 0x80; - ASSERT.equal(1.793662034335766e-43, buffer.readFloatBE(0)); - ASSERT.equal(0, buffer.readFloatLE(0)); - ASSERT.equal(true, 1 / buffer.readFloatLE(0) < 0); - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0x80; - buffer[3] = 0x7f; - ASSERT.equal(4.609571298396486e-41, buffer.readFloatBE(0)); - ASSERT.equal(Infinity, buffer.readFloatLE(0)); - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0x80; - buffer[3] = 0xff; - ASSERT.equal(4.627507918739843e-41, buffer.readFloatBE(0)); - ASSERT.equal(-Infinity, buffer.readFloatLE(0)); -} - - -test(Buffer); diff --git a/test/simple/test-readint.js b/test/simple/test-readint.js deleted file mode 100644 index f1b79e816..000000000 --- a/test/simple/test-readint.js +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * Tests to verify we're reading in signed integers correctly - */ -var common = require('../common'); -var ASSERT = require('assert'); - -/* - * Test 8 bit signed integers - */ -function test8(clazz) { - var data = new clazz(4); - - data[0] = 0x23; - ASSERT.equal(0x23, data.readInt8(0)); - - data[0] = 0xff; - ASSERT.equal(-1, data.readInt8(0)); - - data[0] = 0x87; - data[1] = 0xab; - data[2] = 0x7c; - data[3] = 0xef; - ASSERT.equal(-121, data.readInt8(0)); - ASSERT.equal(-85, data.readInt8(1)); - ASSERT.equal(124, data.readInt8(2)); - ASSERT.equal(-17, data.readInt8(3)); -} - - -function test16(clazz) { - var buffer = new clazz(6); - - buffer[0] = 0x16; - buffer[1] = 0x79; - ASSERT.equal(0x1679, buffer.readInt16BE(0)); - ASSERT.equal(0x7916, buffer.readInt16LE(0)); - - buffer[0] = 0xff; - buffer[1] = 0x80; - ASSERT.equal(-128, buffer.readInt16BE(0)); - ASSERT.equal(-32513, buffer.readInt16LE(0)); - - /* test offset with weenix */ - buffer[0] = 0x77; - buffer[1] = 0x65; - buffer[2] = 0x65; - buffer[3] = 0x6e; - buffer[4] = 0x69; - buffer[5] = 0x78; - ASSERT.equal(0x7765, buffer.readInt16BE(0)); - ASSERT.equal(0x6565, buffer.readInt16BE(1)); - ASSERT.equal(0x656e, buffer.readInt16BE(2)); - ASSERT.equal(0x6e69, buffer.readInt16BE(3)); - ASSERT.equal(0x6978, buffer.readInt16BE(4)); - ASSERT.equal(0x6577, buffer.readInt16LE(0)); - ASSERT.equal(0x6565, buffer.readInt16LE(1)); - ASSERT.equal(0x6e65, buffer.readInt16LE(2)); - ASSERT.equal(0x696e, buffer.readInt16LE(3)); - ASSERT.equal(0x7869, buffer.readInt16LE(4)); -} - - -function test32(clazz) { - var buffer = new clazz(6); - - buffer[0] = 0x43; - buffer[1] = 0x53; - buffer[2] = 0x16; - buffer[3] = 0x79; - ASSERT.equal(0x43531679, buffer.readInt32BE(0)); - ASSERT.equal(0x79165343, buffer.readInt32LE(0)); - - buffer[0] = 0xff; - buffer[1] = 0xfe; - buffer[2] = 0xef; - buffer[3] = 0xfa; - ASSERT.equal(-69638, buffer.readInt32BE(0)); - ASSERT.equal(-84934913, buffer.readInt32LE(0)); - - buffer[0] = 0x42; - buffer[1] = 0xc3; - buffer[2] = 0x95; - buffer[3] = 0xa9; - buffer[4] = 0x36; - buffer[5] = 0x17; - ASSERT.equal(0x42c395a9, buffer.readInt32BE(0)); - ASSERT.equal(-1013601994, buffer.readInt32BE(1)); - ASSERT.equal(-1784072681, buffer.readInt32BE(2)); - ASSERT.equal(-1449802942, buffer.readInt32LE(0)); - ASSERT.equal(917083587, buffer.readInt32LE(1)); - ASSERT.equal(389458325, buffer.readInt32LE(2)); -} - - -test8(Buffer); -test16(Buffer); -test32(Buffer); diff --git a/test/simple/test-readline-interface.js b/test/simple/test-readline-interface.js deleted file mode 100644 index b86dd5a8a..000000000 --- a/test/simple/test-readline-interface.js +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var assert = require('assert'); -var readline = require('readline'); -var EventEmitter = require('events').EventEmitter; -var inherits = require('util').inherits; - -function FakeInput() { - EventEmitter.call(this); -} -inherits(FakeInput, EventEmitter); -FakeInput.prototype.resume = function() {}; -FakeInput.prototype.pause = function() {}; -FakeInput.prototype.write = function() {}; -FakeInput.prototype.end = function() {}; - -function isWarned(emitter) { - for (var name in emitter) { - var listeners = emitter[name]; - if (listeners.warned) return true; - } - return false; -} - -[ true, false ].forEach(function(terminal) { - var fi; - var rli; - var called; - - // sending a full line - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - called = false; - rli.on('line', function(line) { - called = true; - assert.equal(line, 'asdf'); - }); - fi.emit('data', 'asdf\n'); - assert.ok(called); - - // sending a blank line - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - called = false; - rli.on('line', function(line) { - called = true; - assert.equal(line, ''); - }); - fi.emit('data', '\n'); - assert.ok(called); - - // sending a single character with no newline - fi = new FakeInput(); - rli = new readline.Interface(fi, {}); - called = false; - rli.on('line', function(line) { - called = true; - }); - fi.emit('data', 'a'); - assert.ok(!called); - rli.close(); - - // sending a single character with no newline and then a newline - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - called = false; - rli.on('line', function(line) { - called = true; - assert.equal(line, 'a'); - }); - fi.emit('data', 'a'); - assert.ok(!called); - fi.emit('data', '\n'); - assert.ok(called); - rli.close(); - - // sending multiple newlines at once - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - var expectedLines = ['foo', 'bar', 'baz']; - var callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - fi.emit('data', expectedLines.join('\n') + '\n'); - assert.equal(callCount, expectedLines.length); - rli.close(); - - // sending multiple newlines at once that does not end with a new line - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - expectedLines = ['foo', 'bar', 'baz', 'bat']; - callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - fi.emit('data', expectedLines.join('\n')); - assert.equal(callCount, expectedLines.length - 1); - rli.close(); - - // sending multiple newlines at once that does not end with a new(empty) - // line and a `end` event - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - expectedLines = ['foo', 'bar', 'baz', '']; - callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - rli.on('close', function() { - callCount++; - }) - fi.emit('data', expectedLines.join('\n')); - fi.emit('end'); - assert.equal(callCount, expectedLines.length); - rli.close(); - - // sending multiple newlines at once that does not end with a new line - // and a `end` event(last line is) - - // \r\n should emit one line event, not two - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - expectedLines = ['foo', 'bar', 'baz', 'bat']; - callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - fi.emit('data', expectedLines.join('\r\n')); - assert.equal(callCount, expectedLines.length - 1); - rli.close(); - - // \r\n should emit one line event when split across multiple writes. - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - expectedLines = ['foo', 'bar', 'baz', 'bat']; - callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - expectedLines.forEach(function(line) { - fi.emit('data', line + '\r'); - fi.emit('data', '\n'); - }); - assert.equal(callCount, expectedLines.length); - rli.close(); - - // \r should behave like \n when alone - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: true }); - expectedLines = ['foo', 'bar', 'baz', 'bat']; - callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - fi.emit('data', expectedLines.join('\r')); - assert.equal(callCount, expectedLines.length - 1); - rli.close(); - - // \r at start of input should output blank line - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: true }); - expectedLines = ['', 'foo' ]; - callCount = 0; - rli.on('line', function(line) { - assert.equal(line, expectedLines[callCount]); - callCount++; - }); - fi.emit('data', '\rfoo\r'); - assert.equal(callCount, expectedLines.length); - rli.close(); - - // sending a multi-byte utf8 char over multiple writes - var buf = Buffer('☮', 'utf8'); - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - callCount = 0; - rli.on('line', function(line) { - callCount++; - assert.equal(line, buf.toString('utf8')); - }); - [].forEach.call(buf, function(i) { - fi.emit('data', Buffer([i])); - }); - assert.equal(callCount, 0); - fi.emit('data', '\n'); - assert.equal(callCount, 1); - rli.close(); - - // keypress - [ - ['a'], - ['\x1b'], - ['\x1b[31m'], - ['\x1b[31m', '\x1b[39m'], - ['\x1b[31m', 'a', '\x1b[39m', 'a'] - ].forEach(function (keypresses) { - fi = new FakeInput(); - callCount = 0; - var remainingKeypresses = keypresses.slice(); - function keypressListener (ch, key) { - callCount++; - if (ch) assert(!key.code); - assert.equal(key.sequence, remainingKeypresses.shift()); - }; - readline.emitKeypressEvents(fi); - fi.on('keypress', keypressListener); - fi.emit('data', keypresses.join('')); - assert.equal(callCount, keypresses.length); - assert.equal(remainingKeypresses.length, 0); - fi.removeListener('keypress', keypressListener); - fi.emit('data', ''); // removes listener - }); - - if (terminal) { - // question - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - expectedLines = ['foo']; - rli.question(expectedLines[0], function() { - rli.close(); - }); - var cursorPos = rli._getCursorPos(); - assert.equal(cursorPos.rows, 0); - assert.equal(cursorPos.cols, expectedLines[0].length); - rli.close(); - - // sending a multi-line question - fi = new FakeInput(); - rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); - expectedLines = ['foo', 'bar']; - rli.question(expectedLines.join('\n'), function() { - rli.close(); - }); - var cursorPos = rli._getCursorPos(); - assert.equal(cursorPos.rows, expectedLines.length - 1); - assert.equal(cursorPos.cols, expectedLines.slice(-1)[0].length); - rli.close(); - } - - // wide characters should be treated as two columns. - assert.equal(readline.isFullWidthCodePoint('a'.charCodeAt(0)), false); - assert.equal(readline.isFullWidthCodePoint('あ'.charCodeAt(0)), true); - assert.equal(readline.isFullWidthCodePoint('谢'.charCodeAt(0)), true); - assert.equal(readline.isFullWidthCodePoint('고'.charCodeAt(0)), true); - assert.equal(readline.isFullWidthCodePoint(0x1f251), true); // surrogate - assert.equal(readline.codePointAt('ABC', 0), 0x41); - assert.equal(readline.codePointAt('あいう', 1), 0x3044); - assert.equal(readline.codePointAt('\ud800\udc00', 0), // surrogate - 0x10000); - assert.equal(readline.codePointAt('\ud800\udc00A', 2), // surrogate - 0x41); - assert.equal(readline.getStringWidth('abcde'), 5); - assert.equal(readline.getStringWidth('古池や'), 6); - assert.equal(readline.getStringWidth('ノード.js'), 9); - assert.equal(readline.getStringWidth('你好'), 4); - assert.equal(readline.getStringWidth('안녕하세요'), 10); - assert.equal(readline.getStringWidth('A\ud83c\ude00BC'), 5); // surrogate - - // check if vt control chars are stripped - assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> '); - assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > '); - assert.equal(readline.stripVTControlCharacters('\u001b[31m\u001b[39m'), ''); - assert.equal(readline.stripVTControlCharacters('> '), '> '); - assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m'), 2); - assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m> '), 4); - assert.equal(readline.getStringWidth('\u001b[31m\u001b[39m'), 0); - assert.equal(readline.getStringWidth('> '), 2); - - assert.deepEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); - - // check EventEmitter memory leak - for (var i=0; i<12; i++) { - var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout - }); - rl.close(); - assert.equal(isWarned(process.stdin._events), false); - assert.equal(isWarned(process.stdout._events), false); - } - - //can create a new readline Interface with a null output arugument - fi = new FakeInput(); - rli = new readline.Interface({input: fi, output: null, terminal: terminal }); - - called = false; - rli.on('line', function(line) { - called = true; - assert.equal(line, 'asdf'); - }); - fi.emit('data', 'asdf\n'); - assert.ok(called); - - assert.doesNotThrow(function() { - rli.setPrompt("ddd> "); - }); - - assert.doesNotThrow(function() { - rli.prompt(); - }); - - assert.doesNotThrow(function() { - rli.write('really shouldnt be seeing this'); - }); - - assert.doesNotThrow(function() { - rli.question("What do you think of node.js? ", function(answer) { - console.log("Thank you for your valuable feedback:", answer); - rli.close(); - }) - }); - -}); - diff --git a/test/simple/test-readline-set-raw-mode.js b/test/simple/test-readline-set-raw-mode.js deleted file mode 100644 index f43443857..000000000 --- a/test/simple/test-readline-set-raw-mode.js +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var assert = require('assert'); -var readline = require('readline'); -var Stream = require('stream'); - -var stream = new Stream(); -var expectedRawMode = true; -var rawModeCalled = false; -var resumeCalled = false; -var pauseCalled = false; - -stream.setRawMode = function(mode) { - rawModeCalled = true; - assert.equal(mode, expectedRawMode); -}; -stream.resume = function() { - resumeCalled = true; -}; -stream.pause = function() { - pauseCalled = true; -}; - -// when the "readline" starts in "terminal" mode, -// then setRawMode(true) should be called -var rli = readline.createInterface({ - input: stream, - output: stream, - terminal: true -}); -assert(rli.terminal); -assert(rawModeCalled); -assert(resumeCalled); -assert(!pauseCalled); - - -// pause() should call *not* call setRawMode() -rawModeCalled = false; -resumeCalled = false; -pauseCalled = false; -rli.pause(); -assert(!rawModeCalled); -assert(!resumeCalled); -assert(pauseCalled); - - -// resume() should *not* call setRawMode() -rawModeCalled = false; -resumeCalled = false; -pauseCalled = false; -rli.resume(); -assert(!rawModeCalled); -assert(resumeCalled); -assert(!pauseCalled); - - -// close() should call setRawMode(false) -expectedRawMode = false; -rawModeCalled = false; -resumeCalled = false; -pauseCalled = false; -rli.close(); -assert(rawModeCalled); -assert(!resumeCalled); -assert(pauseCalled); - -assert.deepEqual(stream.listeners('keypress'), []); -// one data listener for the keypress events. -assert.equal(stream.listeners('data').length, 1); diff --git a/test/simple/test-readuint.js b/test/simple/test-readuint.js deleted file mode 100644 index 2b11a61c9..000000000 --- a/test/simple/test-readuint.js +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * A battery of tests to help us read a series of uints - */ - -var common = require('../common'); -var ASSERT = require('assert'); - -/* - * We need to check the following things: - * - We are correctly resolving big endian (doesn't mean anything for 8 bit) - * - Correctly resolving little endian (doesn't mean anything for 8 bit) - * - Correctly using the offsets - * - Correctly interpreting values that are beyond the signed range as unsigned - */ -function test8(clazz) { - var data = new clazz(4); - - data[0] = 23; - data[1] = 23; - data[2] = 23; - data[3] = 23; - ASSERT.equal(23, data.readUInt8(0)); - ASSERT.equal(23, data.readUInt8(1)); - ASSERT.equal(23, data.readUInt8(2)); - ASSERT.equal(23, data.readUInt8(3)); - - data[0] = 255; /* If it became a signed int, would be -1 */ - ASSERT.equal(255, data.readUInt8(0)); -} - - -/* - * Test 16 bit unsigned integers. We need to verify the same set as 8 bit, only - * now some of the issues actually matter: - * - We are correctly resolving big endian - * - Correctly resolving little endian - * - Correctly using the offsets - * - Correctly interpreting values that are beyond the signed range as unsigned - */ -function test16(clazz) { - var data = new clazz(4); - - data[0] = 0; - data[1] = 0x23; - data[2] = 0x42; - data[3] = 0x3f; - ASSERT.equal(0x23, data.readUInt16BE(0)); - ASSERT.equal(0x2342, data.readUInt16BE(1)); - ASSERT.equal(0x423f, data.readUInt16BE(2)); - ASSERT.equal(0x2300, data.readUInt16LE(0)); - ASSERT.equal(0x4223, data.readUInt16LE(1)); - ASSERT.equal(0x3f42, data.readUInt16LE(2)); - - data[0] = 0xfe; - data[1] = 0xfe; - ASSERT.equal(0xfefe, data.readUInt16BE(0)); - ASSERT.equal(0xfefe, data.readUInt16LE(0)); -} - - -/* - * Test 32 bit unsigned integers. We need to verify the same set as 8 bit, only - * now some of the issues actually matter: - * - We are correctly resolving big endian - * - Correctly using the offsets - * - Correctly interpreting values that are beyond the signed range as unsigned - */ -function test32(clazz) { - var data = new clazz(8); - - data[0] = 0x32; - data[1] = 0x65; - data[2] = 0x42; - data[3] = 0x56; - data[4] = 0x23; - data[5] = 0xff; - ASSERT.equal(0x32654256, data.readUInt32BE(0)); - ASSERT.equal(0x65425623, data.readUInt32BE(1)); - ASSERT.equal(0x425623ff, data.readUInt32BE(2)); - ASSERT.equal(0x56426532, data.readUInt32LE(0)); - ASSERT.equal(0x23564265, data.readUInt32LE(1)); - ASSERT.equal(0xff235642, data.readUInt32LE(2)); -} - - -test8(Buffer); -test16(Buffer); -test32(Buffer); diff --git a/test/simple/test-regress-GH-1531.js b/test/simple/test-regress-GH-1531.js deleted file mode 100644 index 53bc2a3ca..000000000 --- a/test/simple/test-regress-GH-1531.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var https = require('https'); -var assert = require('assert'); -var fs = require('fs'); -var common = require('../common'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var gotCallback = false; - -var server = https.createServer(options, function(req, res) { - res.writeHead(200); - res.end('hello world\n'); -}); - -server.listen(common.PORT, function() { - console.error('listening'); - https.get({ - agent: false, - path: '/', - port: common.PORT, - rejectUnauthorized: false - }, function(res) { - console.error(res.statusCode, res.headers); - gotCallback = true; - res.resume(); - server.close(); - }).on('error', function(e) { - console.error(e.stack); - process.exit(1); - }); -}); - -process.on('exit', function() { - assert.ok(gotCallback); - console.log('ok'); -}); - diff --git a/test/simple/test-regress-GH-1697.js b/test/simple/test-regress-GH-1697.js deleted file mode 100644 index fdf2c42e9..000000000 --- a/test/simple/test-regress-GH-1697.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var net = require('net'), - cp = require('child_process'), - util = require('util'); - -if (process.argv[2] === 'server') { - // Server - - var server = net.createServer(function(conn) { - conn.on('data', function(data) { - console.log('server received ' + data.length + ' bytes'); - }); - - conn.on('close', function() { - server.close(); - }); - }); - - server.listen(common.PORT, '127.0.0.1', function() { - console.log('Server running.'); - }); - -} else { - // Client - - var serverProcess = cp.spawn(process.execPath, [process.argv[1], 'server']); - serverProcess.stdout.pipe(process.stdout); - serverProcess.stderr.pipe(process.stdout); - - serverProcess.stdout.once('data', function() { - var client = net.createConnection(common.PORT, '127.0.0.1'); - client.on('connect', function() { - var alot = new Buffer(1024), - alittle = new Buffer(1); - - for (var i = 0; i < 100; i++) { - client.write(alot); - } - - // Block the event loop for 1 second - var start = (new Date()).getTime(); - while ((new Date).getTime() < start + 1000) {} - - client.write(alittle); - - client.destroySoon(); - }); - }); -} diff --git a/test/simple/test-regress-GH-1726.js b/test/simple/test-regress-GH-1726.js deleted file mode 100644 index f65e63d10..000000000 --- a/test/simple/test-regress-GH-1726.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// 'Software'), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Open a chain of five Node processes each a child of the next. The final -// process exits immediately. Each process in the chain is instructed to -// exit when its child exits. -// https://github.com/joyent/node/issues/1726 - -var common = require('../common'); -var assert = require('assert'); -var ch = require('child_process'); - -var gen = +(process.argv[2] || 0); -var maxGen = 5; - - -if (gen === maxGen) { - console.error('hit maxGen, exiting', maxGen); - return; -} - -var child = ch.spawn(process.execPath, [__filename, gen + 1], { - stdio: [ 'ignore', 'pipe', 'ignore' ] -}); -assert.ok(!child.stdin); -assert.ok(child.stdout); -assert.ok(!child.stderr); - -console.error('gen=%d, pid=%d', gen, process.pid); - -/* -var timer = setTimeout(function () { - throw new Error('timeout! gen='+gen); -}, 1000); -*/ - -child.on('exit', function(code) { - console.error('exit %d from gen %d', code, gen + 1); - //clearTimeout(timer); -}); - -child.stdout.pipe(process.stdout); - -child.stdout.on('close', function() { - console.error('child.stdout close gen=%d', gen); -}); diff --git a/test/simple/test-regress-GH-1899.js b/test/simple/test-regress-GH-1899.js deleted file mode 100644 index 7fc8007a2..000000000 --- a/test/simple/test-regress-GH-1899.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var path = require('path'); -var assert = require('assert'); -var spawn = require('child_process').spawn; -var common = require('../common'); - -var child = spawn(process.argv[0], [ - path.join(common.fixturesDir, 'GH-1899-output.js') -]); -var output = ''; - -child.stdout.on('data', function(data) { - output += data; -}); - -child.on('exit', function(code, signal) { - assert.equal(code, 0); - assert.equal(output, 'hello, world!\n'); -}); - diff --git a/test/simple/test-regress-GH-3542.js b/test/simple/test-regress-GH-3542.js deleted file mode 100644 index 90e0b7850..000000000 --- a/test/simple/test-regress-GH-3542.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This test is only relevant on Windows. -if (process.platform !== 'win32') { - return process.exit(0); -} - -var common = require('../common.js'), - assert = require('assert'), - fs = require('fs'), - path = require('path'), - succeeded = 0; - -function test(p) { - var result = fs.realpathSync(p); - assert.strictEqual(result, path.resolve(p)); - - fs.realpath(p, function(err, result) { - assert.ok(!err); - assert.strictEqual(result, path.resolve(p)); - succeeded++; - }); -} - -test('//localhost/c$/windows/system32'); -test('//localhost/c$/windows'); -test('//localhost/c$/') -test('\\\\localhost\\c$') -test('c:\\'); -test('c:'); -test(process.env.windir); - -process.on('exit', function() { - assert.strictEqual(succeeded, 7); -}); \ No newline at end of file diff --git a/test/simple/test-regress-GH-3739.js b/test/simple/test-regress-GH-3739.js deleted file mode 100644 index 937068795..000000000 --- a/test/simple/test-regress-GH-3739.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'), - assert = require('assert'), - fs = require('fs'), - path = require('path'); - -var dir = path.resolve(common.fixturesDir), - dirs = []; - -// Make a long path. -for (var i = 0; i < 50; i++) { - dir = dir + '/123456790'; - try { - fs.mkdirSync(dir, '0777'); - } catch (e) { - if (e.code == 'EEXIST') { - // Ignore; - } else { - cleanup(); - throw e; - } - } - dirs.push(dir); -} - -// Test existsSync -var r = fs.existsSync(dir); -if (r !== true) { - cleanup(); - throw new Error('fs.existsSync returned false'); -} - -// Text exists -fs.exists(dir, function(r) { - cleanup(); - if (r !== true) { - throw new Error('fs.exists reported false'); - } -}); - -// Remove all created directories -function cleanup() { - for (var i = dirs.length - 1; i >= 0; i--) { - fs.rmdirSync(dirs[i]); - } -} diff --git a/test/simple/test-regress-GH-4015.js b/test/simple/test-regress-GH-4015.js deleted file mode 100644 index b66584f80..000000000 --- a/test/simple/test-regress-GH-4015.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; - -var cmd = process.execPath - + ' ' - + common.fixturesDir - + '/test-regress-GH-4015.js'; - -exec(cmd, function(err, stdout, stderr) { - assert(/RangeError: Maximum call stack size exceeded/.test(stderr)); -}); diff --git a/test/simple/test-regress-GH-4027.js b/test/simple/test-regress-GH-4027.js deleted file mode 100644 index 3dff1684d..000000000 --- a/test/simple/test-regress-GH-4027.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var filename = path.join(common.tmpDir, 'watched'); -fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); -setTimeout(fs.unlinkSync, 100, filename); - -var seenEvent = 0; -process.on('exit', function() { - assert.equal(seenEvent, 1); -}); - -fs.watchFile(filename, { interval: 50 }, function(curr, prev) { - assert.equal(prev.nlink, 1); - assert.equal(curr.nlink, 0); - fs.unwatchFile(filename); - seenEvent++; -}); diff --git a/test/simple/test-regress-GH-4256.js b/test/simple/test-regress-GH-4256.js deleted file mode 100644 index 9f937cc09..000000000 --- a/test/simple/test-regress-GH-4256.js +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -process.domain = null; -timer = setTimeout(function() { - console.log("this console.log statement should not make node crash"); -}, 1); diff --git a/test/simple/test-regress-GH-4948.js b/test/simple/test-regress-GH-4948.js deleted file mode 100644 index 5e717fad5..000000000 --- a/test/simple/test-regress-GH-4948.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// https://github.com/joyent/node/issues/4948 - -var common = require('../common'); -var http = require('http'); - -var reqCount = 0; -var server = http.createServer(function(serverReq, serverRes){ - if (reqCount) { - serverRes.end(); - server.close(); - return; - } - reqCount = 1; - - - // normally the use case would be to call an external site - // does not require connecting locally or to itself to fail - var r = http.request({hostname: 'localhost', port: common.PORT}, function(res) { - // required, just needs to be in the client response somewhere - serverRes.end(); - - // required for test to fail - res.on('data', function(data) { }); - - }); - r.on('error', function(e) {}); - r.end(); - - serverRes.write('some data'); -}).listen(common.PORT); - -// simulate a client request that closes early -var net = require('net'); - -var sock = new net.Socket(); -sock.connect(common.PORT, 'localhost'); - -sock.on('connect', function() { - sock.write('GET / HTTP/1.1\r\n\r\n'); - sock.end(); -}); \ No newline at end of file diff --git a/test/simple/test-regress-GH-5927.js b/test/simple/test-regress-GH-5927.js deleted file mode 100644 index 5f8f27661..000000000 --- a/test/simple/test-regress-GH-5927.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var readline = require('readline'); - -var rl = readline.createInterface(process.stdin, process.stdout); -rl.resume(); - -var hasPaused = false; - -var origPause = rl.pause; -rl.pause = function() { - hasPaused = true; - origPause.apply(this, arguments); -} - -var origSetRawMode = rl._setRawMode; -rl._setRawMode = function(mode) { - assert.ok(hasPaused); - origSetRawMode.apply(this, arguments); -} - -rl.close(); diff --git a/test/simple/test-regress-GH-6235.js b/test/simple/test-regress-GH-6235.js deleted file mode 100644 index e830f7bbe..000000000 --- a/test/simple/test-regress-GH-6235.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -assert.doesNotThrow(function() { - require('vm').runInNewContext('"use strict"; var v = 1; v = 2'); -}); diff --git a/test/simple/test-regress-GH-746.js b/test/simple/test-regress-GH-746.js deleted file mode 100644 index 29f145652..000000000 --- a/test/simple/test-regress-GH-746.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Just test that destroying stdin doesn't mess up listening on a server. -// This is a regression test for GH-746. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); - -process.stdin.destroy(); - -var accepted = null; -var server = net.createServer(function(socket) { - console.log('accepted'); - accepted = socket; - socket.end(); - server.close(); -}); - - -server.listen(common.PORT, function() { - console.log('listening...'); - - net.createConnection(common.PORT); -}); - - -process.on('exit', function() { - assert.ok(accepted); -}); - diff --git a/test/simple/test-regress-GH-7511.js b/test/simple/test-regress-GH-7511.js deleted file mode 100644 index 9694f0499..000000000 --- a/test/simple/test-regress-GH-7511.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - vm = require('vm'); - -assert.doesNotThrow(function() { - var context = vm.createContext({ process: process }); - var result = vm.runInContext('process.env["PATH"]', context); - assert.notEqual(undefined, result); -}); diff --git a/test/simple/test-regress-GH-784.js b/test/simple/test-regress-GH-784.js deleted file mode 100644 index c2039a9c6..000000000 --- a/test/simple/test-regress-GH-784.js +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Regression test for GH-784 -// https://github.com/joyent/node/issues/784 -// -// The test works by making a total of 8 requests to the server. The first -// two are made with the server off - they should come back as ECONNREFUSED. -// The next two are made with server on - they should come back successful. -// The next two are made with the server off - and so on. Without the fix -// we were experiencing parse errors and instead of ECONNREFUSED. -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); - - -var server = http.createServer(function(req, res) { - var body = ''; - - req.setEncoding('utf8'); - req.on('data', function(chunk) { - body += chunk; - }); - - req.on('end', function() { - assert.equal('PING', body); - res.writeHead(200); - res.end('PONG'); - }); -}); - - -server.on('listening', pingping); - - -function serverOn() { - console.error('Server ON'); - server.listen(common.PORT); -} - - -function serverOff() { - console.error('Server OFF'); - server.close(); - pingping(); -} - -var responses = []; - - -function afterPing(result) { - responses.push(result); - console.error('afterPing. responses.length = ' + responses.length); - switch (responses.length) { - case 2: - assert.ok(/ECONNREFUSED/.test(responses[0])); - assert.ok(/ECONNREFUSED/.test(responses[1])); - serverOn(); - break; - - case 4: - assert.ok(/success/.test(responses[2])); - assert.ok(/success/.test(responses[3])); - serverOff(); - break; - - case 6: - assert.ok(/ECONNREFUSED/.test(responses[4])); - assert.ok(/ECONNREFUSED/.test(responses[5])); - serverOn(); - break; - - case 8: - assert.ok(/success/.test(responses[6])); - assert.ok(/success/.test(responses[7])); - server.close(); - // we should go to process.on('exit') from here. - break; - } -} - - -function ping() { - console.error('making req'); - - var opt = { - port: common.PORT, - path: '/ping', - method: 'POST' - }; - - var req = http.request(opt, function(res) { - var body = ''; - - res.setEncoding('utf8'); - res.on('data', function(chunk) { - body += chunk; - }); - - res.on('end', function() { - assert.equal('PONG', body); - assert.ok(!hadError); - gotEnd = true; - afterPing('success'); - }); - }); - - req.end('PING'); - - var gotEnd = false; - var hadError = false; - - req.on('error', function(error) { - console.log('Error making ping req: ' + error); - hadError = true; - assert.ok(!gotEnd); - afterPing(error.message); - }); -} - - - -function pingping() { - ping(); - ping(); -} - - -pingping(); - - - - -process.on('exit', function() { - console.error("process.on('exit')"); - console.error(responses); - - assert.equal(8, responses.length); -}); diff --git a/test/simple/test-regress-GH-819.js b/test/simple/test-regress-GH-819.js deleted file mode 100644 index 874d99e28..000000000 --- a/test/simple/test-regress-GH-819.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var net = require('net'); -var assert = require('assert'); - -// Connect to something that we need to DNS resolve -var c = net.createConnection(80, 'google.com'); -c.destroy(); diff --git a/test/simple/test-regress-GH-877.js b/test/simple/test-regress-GH-877.js deleted file mode 100644 index 30e1f8009..000000000 --- a/test/simple/test-regress-GH-877.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var http = require('http'); -var assert = require('assert'); - -var N = 20; -var responses = 0; -var maxQueued = 0; - -var agent = http.globalAgent; -agent.maxSockets = 10; - -var server = http.createServer(function(req, res) { - res.writeHead(200); - res.end('Hello World\n'); -}); - -var addrString = agent.getName({ host: '127.0.0.1', port: common.PORT }); - -server.listen(common.PORT, '127.0.0.1', function() { - for (var i = 0; i < N; i++) { - var options = { - host: '127.0.0.1', - port: common.PORT - }; - - var req = http.get(options, function(res) { - if (++responses == N) { - server.close(); - } - res.resume(); - }); - - assert.equal(req.agent, agent); - - console.log('Socket: ' + agent.sockets[addrString].length + '/' + - agent.maxSockets + ' queued: ' + (agent.requests[addrString] ? - agent.requests[addrString].length : 0)); - - var agentRequests = agent.requests[addrString] ? - agent.requests[addrString].length : 0; - - if (maxQueued < agentRequests) { - maxQueued = agentRequests; - } - } -}); - -process.on('exit', function() { - assert.ok(responses == N); - assert.ok(maxQueued <= 10); -}); diff --git a/test/simple/test-regress-GH-897.js b/test/simple/test-regress-GH-897.js deleted file mode 100644 index dd4399f16..000000000 --- a/test/simple/test-regress-GH-897.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var t = Date.now(); -var diff; -setTimeout(function() { - diff = Date.now() - t; - console.error(diff); -}, 0.1); - - -process.on('exit', function() { - assert.ok(diff < 100); -}); diff --git a/test/simple/test-regression-object-prototype.js b/test/simple/test-regression-object-prototype.js deleted file mode 100644 index 158532ad8..000000000 --- a/test/simple/test-regression-object-prototype.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -//console.log('puts before'); - -Object.prototype.xadsadsdasasdxx = function() { -}; - -console.log('puts after'); diff --git a/test/simple/test-repl-.save.load.js b/test/simple/test-repl-.save.load.js deleted file mode 100644 index fdbf18fa0..000000000 --- a/test/simple/test-repl-.save.load.js +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var util = require('util'); -var join = require('path').join; -var fs = require('fs'); -var common = require('../common'); - -var repl = require('repl'); - -// A stream to push an array into a REPL -function ArrayStream() { - this.run = function(data) { - var self = this; - data.forEach(function(line) { - self.emit('data', line + '\n'); - }); - } -} -util.inherits(ArrayStream, require('stream').Stream); -ArrayStream.prototype.readable = true; -ArrayStream.prototype.writable = true; -ArrayStream.prototype.resume = function() {}; -ArrayStream.prototype.write = function() {}; - -var works = [['inner.one'], 'inner.o']; - -var putIn = new ArrayStream(); -var testMe = repl.start('', putIn); - - -var testFile = [ - 'var top = function () {', - 'var inner = {one:1};' -]; -var saveFileName = join(common.tmpDir, 'test.save.js'); - -// input some data -putIn.run(testFile); - -// save it to a file -putIn.run(['.save ' + saveFileName]); - -// the file should have what I wrote -assert.equal(fs.readFileSync(saveFileName, 'utf8'), testFile.join('\n') + '\n'); - -// make sure that the REPL data is "correct" -// so when I load it back I know I'm good -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -// clear the REPL -putIn.run(['.clear']); - -// Load the file back in -putIn.run(['.load ' + saveFileName]); - -// make sure that the REPL data is "correct" -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -// clear the REPL -putIn.run(['.clear']); - -var loadFile = join(common.tmpDir, 'file.does.not.exist'); - -// should not break -putIn.write = function(data) { - // make sure I get a failed to load message and not some crazy error - assert.equal(data, 'Failed to load:' + loadFile + '\n'); - // eat me to avoid work - putIn.write = function() {}; -}; -putIn.run(['.load ' + loadFile]); - - -//TODO how do I do a failed .save test? diff --git a/test/simple/test-repl-autolibs.js b/test/simple/test-repl-autolibs.js deleted file mode 100644 index b6f929471..000000000 --- a/test/simple/test-repl-autolibs.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var util = require('util'); -var repl = require('repl'); - -// A stream to push an array into a REPL -function ArrayStream() { - this.run = function (data) { - var self = this; - data.forEach(function (line) { - self.emit('data', line + '\n'); - }); - } -} -util.inherits(ArrayStream, require('stream').Stream); -ArrayStream.prototype.readable = true; -ArrayStream.prototype.writable = true; -ArrayStream.prototype.resume = function () {}; -ArrayStream.prototype.write = function () {}; - -var putIn = new ArrayStream; -var testMe = repl.start('', putIn, null, true); - -test1(); - -function test1(){ - var gotWrite = false; - putIn.write = function (data) { - gotWrite = true; - if (data.length) { - - // inspect output matches repl output - assert.equal(data, util.inspect(require('fs'), null, 2, false) + '\n'); - // globally added lib matches required lib - assert.equal(global.fs, require('fs')); - test2(); - } - }; - assert(!gotWrite); - putIn.run(['fs']); - assert(gotWrite); -} - -function test2(){ - var gotWrite = false; - putIn.write = function(data) { - gotWrite = true; - if (data.length) { - // repl response error message - assert.equal(data, '{}\n'); - // original value wasn't overwritten - assert.equal(val, global.url); - } - }; - var val = {}; - global.url = val; - assert(!gotWrite); - putIn.run(['url']); - assert(gotWrite); -} diff --git a/test/simple/test-repl-console.js b/test/simple/test-repl-console.js deleted file mode 100644 index 3dca14b7f..000000000 --- a/test/simple/test-repl-console.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - Stream = require('stream'), - repl = require('repl'); - -// create a dummy stream that does nothing -var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; -stream.readable = stream.writable = true; - -var r = repl.start({ - input: stream, - output: stream, - useGlobal: false -}); - - -// ensure that the repl context gets its own "console" instance -assert(r.context.console); - -// ensure that the repl console instance is not the global one -assert.notStrictEqual(r.context.console, console); diff --git a/test/simple/test-repl-domain.js b/test/simple/test-repl-domain.js deleted file mode 100644 index 55b7dc475..000000000 --- a/test/simple/test-repl-domain.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common.js'); - -var util = require('util'); -var repl = require('repl'); - -// A stream to push an array into a REPL -function ArrayStream() { - this.run = function(data) { - var self = this; - data.forEach(function(line) { - self.emit('data', line + '\n'); - }); - } -} -util.inherits(ArrayStream, require('stream').Stream); -ArrayStream.prototype.readable = true; -ArrayStream.prototype.writable = true; -ArrayStream.prototype.resume = function() {}; -ArrayStream.prototype.write = function() {}; - -var putIn = new ArrayStream(); -var testMe = repl.start('', putIn); - -putIn.write = function(data) { - // Don't use assert for this because the domain might catch it, and - // give a false negative. Don't throw, just print and exit. - if (data === 'OK\n') { - console.log('ok'); - } - else { - console.error(data); - process.exit(1); - } -}; - -putIn.run([ - 'require("domain").create().on("error", function () { console.log("OK") })' - + '.run(function () { throw new Error("threw") })' -]); diff --git a/test/simple/test-repl-end-emits-exit.js b/test/simple/test-repl-end-emits-exit.js deleted file mode 100644 index 46eca2efb..000000000 --- a/test/simple/test-repl-end-emits-exit.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - Stream = require('stream'), - repl = require('repl'), - terminalExit = 0, - regularExit = 0; - -// create a dummy stream that does nothing -var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; -stream.readable = stream.writable = true; - -function testTerminalMode() { - var r1 = repl.start({ - input: stream, - output: stream, - terminal: true - }); - - process.nextTick(function() { - // manually fire a ^D keypress - stream.emit('data', '\u0004'); - }); - - r1.on('exit', function() { - // should be fired from the simulated ^D keypress - terminalExit++; - testRegularMode(); - }); -} - -function testRegularMode() { - var r2 = repl.start({ - input: stream, - output: stream, - terminal: false - }); - - process.nextTick(function() { - stream.emit('end'); - }); - - r2.on('exit', function() { - // should be fired from the simulated 'end' event - regularExit++; - }); -} - -process.on('exit', function() { - assert.equal(terminalExit, 1); - assert.equal(regularExit, 1); -}); - - -// start -testTerminalMode(); diff --git a/test/simple/test-repl-harmony.js b/test/simple/test-repl-harmony.js deleted file mode 100644 index 701dd5ed6..000000000 --- a/test/simple/test-repl-harmony.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; -var args = ['--harmony', '--use-strict', '-i']; -var child = spawn(process.execPath, args); - -var input = 'function x(){const y=1;y=2}\n'; -var expectOut = /^> SyntaxError: Assignment to constant variable.\n/; - -child.stderr.setEncoding('utf8'); -child.stderr.on('data', function(c) { - throw new Error('child.stderr be silent'); -}); - -child.stdout.setEncoding('utf8'); -var out = ''; -child.stdout.on('data', function(c) { - out += c; -}); -child.stdout.on('end', function() { - assert(expectOut.test(out)); - console.log('ok'); -}); - -child.stdin.end(input); diff --git a/test/simple/test-repl-options.js b/test/simple/test-repl-options.js deleted file mode 100644 index 94a622da2..000000000 --- a/test/simple/test-repl-options.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - Stream = require('stream'), - repl = require('repl'); - -common.globalCheck = false; - -// create a dummy stream that does nothing -var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; -stream.readable = stream.writable = true; - -// 1, mostly defaults -var r1 = repl.start({ - input: stream, - output: stream, - terminal: true -}); - -assert.equal(r1.input, stream); -assert.equal(r1.output, stream); -assert.equal(r1.input, r1.inputStream); -assert.equal(r1.output, r1.outputStream); -assert.equal(r1.terminal, true); -assert.equal(r1.useColors, r1.terminal); -assert.equal(r1.useGlobal, false); -assert.equal(r1.ignoreUndefined, false); - -// test r1 for backwards compact -assert.equal(r1.rli.input, stream); -assert.equal(r1.rli.output, stream); -assert.equal(r1.rli.input, r1.inputStream); -assert.equal(r1.rli.output, r1.outputStream); -assert.equal(r1.rli.terminal, true); -assert.equal(r1.useColors, r1.rli.terminal); - -// 2 -function writer() {} -function evaler() {} -var r2 = repl.start({ - input: stream, - output: stream, - terminal: false, - useColors: true, - useGlobal: true, - ignoreUndefined: true, - eval: evaler, - writer: writer -}); -assert.equal(r2.input, stream); -assert.equal(r2.output, stream); -assert.equal(r2.input, r2.inputStream); -assert.equal(r2.output, r2.outputStream); -assert.equal(r2.terminal, false); -assert.equal(r2.useColors, true); -assert.equal(r2.useGlobal, true); -assert.equal(r2.ignoreUndefined, true); -assert.equal(r2.writer, writer); - -// test r2 for backwards compact -assert.equal(r2.rli.input, stream); -assert.equal(r2.rli.output, stream); -assert.equal(r2.rli.input, r2.inputStream); -assert.equal(r2.rli.output, r2.outputStream); -assert.equal(r2.rli.terminal, false); - diff --git a/test/simple/test-repl-require-cache.js b/test/simple/test-repl-require-cache.js deleted file mode 100644 index fe5753d21..000000000 --- a/test/simple/test-repl-require-cache.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - repl = require('repl'); - -// https://github.com/joyent/node/issues/3226 - -require.cache.something = 1; -assert.equal(require.cache.something, 1); - -repl.start({ useGlobal: false }).close(); - -assert.equal(require.cache.something, 1); diff --git a/test/simple/test-repl-reset-event.js b/test/simple/test-repl-reset-event.js deleted file mode 100644 index 3554d17b9..000000000 --- a/test/simple/test-repl-reset-event.js +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -common.globalCheck = false; - -var assert = require('assert'); -var repl = require('repl'); -var Stream = require('stream'); - -// create a dummy stream that does nothing -var dummy = new Stream(); -dummy.write = dummy.pause = dummy.resume = function(){}; -dummy.readable = dummy.writable = true; - -function testReset(cb) { - var r = repl.start({ - input: dummy, - output: dummy, - useGlobal: false - }); - r.context.foo = 42; - r.on('reset', function(context) { - assert(!!context, 'REPL did not emit a context with reset event'); - assert.equal(context, r.context, 'REPL emitted incorrect context'); - assert.equal(context.foo, undefined, 'REPL emitted the previous context, and is not using global as context'); - context.foo = 42; - cb(); - }); - r.resetContext(); -} - -function testResetGlobal(cb) { - var r = repl.start({ - input: dummy, - output: dummy, - useGlobal: true - }); - r.context.foo = 42; - r.on('reset', function(context) { - assert.equal(context.foo, 42, '"foo" property is missing from REPL using global as context'); - cb(); - }); - r.resetContext(); -} - -var timeout = setTimeout(function() { - assert.fail('Timeout, REPL did not emit reset events'); -}, 5000); - -testReset(function() { - testResetGlobal(function() { - clearTimeout(timeout); - }); -}); diff --git a/test/simple/test-repl-setprompt.js b/test/simple/test-repl-setprompt.js deleted file mode 100644 index e5021c235..000000000 --- a/test/simple/test-repl-setprompt.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'), - assert = require('assert'), - spawn = require('child_process').spawn, - os = require('os'), - util = require('util'); - -var args = [ - '-e', - 'var e = new (require("repl")).REPLServer("foo.. "); e.context.e = e;', -]; - -var p = "bar.. "; - -var child = spawn(process.execPath, args); - -child.stdout.setEncoding('utf8'); - -var data = ''; -child.stdout.on('data', function(d) { data += d }); - -child.stdin.end(util.format("e.setPrompt('%s');%s", p, os.EOL)); - -child.on('close', function(code, signal) { - assert.strictEqual(code, 0); - assert.ok(!signal); - var lines = data.split(/\n/); - assert.strictEqual(lines.pop(), p); -}); diff --git a/test/simple/test-repl-syntax-error-handling.js b/test/simple/test-repl-syntax-error-handling.js deleted file mode 100644 index 74328f449..000000000 --- a/test/simple/test-repl-syntax-error-handling.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -switch (process.argv[2]) { - case 'child': - return child(); - case undefined: - return parent(); - default: - throw new Error('wtf'); -} - -function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); - - child.stderr.setEncoding('utf8'); - child.stderr.on('data', function(c) { - console.error('%j', c); - throw new Error('should not get stderr data'); - }); - - child.stdout.setEncoding('utf8'); - var out = ''; - child.stdout.on('data', function(c) { - out += c; - }); - child.stdout.on('end', function() { - assert.equal(out, '10\n'); - console.log('ok - got expected output'); - }); - - child.on('exit', function(c) { - assert(!c); - console.log('ok - exit success'); - }); -} - -function child() { - var vm = require('vm'); - try { - vm.runInThisContext('haf!@##&$!@$*!@', { displayErrors: false }); - } catch (er) { - var caught = true; - } - assert(caught); - vm.runInThisContext('console.log(10)', { displayErrors: false }); -} diff --git a/test/simple/test-repl-tab-complete.js b/test/simple/test-repl-tab-complete.js deleted file mode 100644 index 48df4033d..000000000 --- a/test/simple/test-repl-tab-complete.js +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); - -var repl = require('repl'); - -// A stream to push an array into a REPL -function ArrayStream() { - this.run = function(data) { - var self = this; - data.forEach(function(line) { - self.emit('data', line + '\n'); - }); - } -} -util.inherits(ArrayStream, require('stream').Stream); -ArrayStream.prototype.readable = true; -ArrayStream.prototype.writable = true; -ArrayStream.prototype.resume = function() {}; -ArrayStream.prototype.write = function() {}; - -var works = [['inner.one'], 'inner.o']; -var doesNotBreak = [[], 'inner.o']; - -var putIn = new ArrayStream(); -var testMe = repl.start('', putIn); - -// Tab Complete will not break in an object literal -putIn.run(['.clear']); -putIn.run([ - 'var inner = {', - 'one:1' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, doesNotBreak); -}); -testMe.complete('console.lo', function(error, data) { - assert.deepEqual(data, [['console.log'], 'console.lo']); -}); - -// Tab Complete will return globaly scoped variables -putIn.run(['};']); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -putIn.run(['.clear']); - -// Tab Complete will not break in an ternary operator with () -putIn.run([ - 'var inner = ( true ' , - '?', - '{one: 1} : ' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, doesNotBreak); -}); - -putIn.run(['.clear']); - -// Tab Complete will return a simple local variable -putIn.run([ - 'var top = function () {', - 'var inner = {one:1};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -// When you close the function scope tab complete will not return the -// locally scoped variable -putIn.run(['};']); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, doesNotBreak); -}); - -putIn.run(['.clear']); - -// Tab Complete will return a complex local variable -putIn.run([ - 'var top = function () {', - 'var inner = {', - ' one:1', - '};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -putIn.run(['.clear']); - -// Tab Complete will return a complex local variable even if the function -// has parameters -putIn.run([ - 'var top = function (one, two) {', - 'var inner = {', - ' one:1', - '};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -putIn.run(['.clear']); - -// Tab Complete will return a complex local variable even if the -// scope is nested inside an immediately executed function -putIn.run([ - 'var top = function () {', - '(function test () {', - 'var inner = {', - ' one:1', - '};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, works); -}); - -putIn.run(['.clear']); - -// currently does not work, but should not break note the inner function -// def has the params and { on a separate line -putIn.run([ - 'var top = function () {', - 'r = function test (', - ' one, two) {', - 'var inner = {', - ' one:1', - '};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, doesNotBreak); -}); - -putIn.run(['.clear']); - -// currently does not work, but should not break, not the { -putIn.run([ - 'var top = function () {', - 'r = function test ()', - '{', - 'var inner = {', - ' one:1', - '};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, doesNotBreak); -}); - -putIn.run(['.clear']); - -// currently does not work, but should not break -putIn.run([ - 'var top = function () {', - 'r = function test (', - ')', - '{', - 'var inner = {', - ' one:1', - '};' -]); -testMe.complete('inner.o', function(error, data) { - assert.deepEqual(data, doesNotBreak); -}); - -putIn.run(['.clear']); - -// make sure tab completion works on non-Objects -putIn.run([ - 'var str = "test";' -]); -testMe.complete('str.len', function(error, data) { - assert.deepEqual(data, [['str.length'], 'str.len']); -}); - -putIn.run(['.clear']); - -// tab completion should not break on spaces -var spaceTimeout = setTimeout(function() { - throw new Error('timeout'); -}, 1000); - -testMe.complete(' ', function(error, data) { - assert.deepEqual(data, [[],undefined]); - clearTimeout(spaceTimeout); -}); - -// tab completion should pick up the global "toString" object, and -// any other properties up the "global" object's prototype chain -testMe.complete('toSt', function(error, data) { - assert.deepEqual(data, [['toString'], 'toSt']); -}); - -// Tab complete provides built in libs for require() -putIn.run(['.clear']); - -testMe.complete('require(\'', function(error, data) { - assert.strictEqual(error, null); - repl._builtinLibs.forEach(function(lib) { - assert.notStrictEqual(data[0].indexOf(lib), -1, lib + ' not found'); - }); -}); - -testMe.complete('require(\'n', function(error, data) { - assert.strictEqual(error, null); - assert.deepEqual(data, [['net'], 'n']); -}); diff --git a/test/simple/test-repl-timeout-throw.js b/test/simple/test-repl-timeout-throw.js deleted file mode 100644 index 28f370909..000000000 --- a/test/simple/test-repl-timeout-throw.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common.js'); - -var spawn = require('child_process').spawn; - -var child = spawn(process.execPath, [ '-i' ], { - stdio: [null, null, 2] -}); - -var stdout = ''; -child.stdout.setEncoding('utf8'); -child.stdout.on('data', function(c) { - process.stdout.write(c); - stdout += c; -}); - -child.stdin.write = function(original) { return function(c) { - process.stderr.write(c); - return original.call(child.stdin, c); -}}(child.stdin.write); - -child.stdout.once('data', function() { - child.stdin.write('var throws = 0;'); - child.stdin.write('process.on("exit",function(){console.log(throws)});'); - child.stdin.write('function thrower(){console.log("THROW",throws++);XXX};'); - child.stdin.write('setTimeout(thrower);""\n'); - - setTimeout(fsTest, 50); - function fsTest() { - var f = JSON.stringify(__filename); - child.stdin.write('fs.readFile(' + f + ', thrower);\n'); - setTimeout(eeTest, 50); - } - - function eeTest() { - child.stdin.write('setTimeout(function() {\n' + - ' var events = require("events");\n' + - ' var e = new events.EventEmitter;\n' + - ' process.nextTick(function() {\n' + - ' e.on("x", thrower);\n' + - ' setTimeout(function() {\n' + - ' e.emit("x");\n' + - ' });\n' + - ' });\n' + - '});"";\n'); - - setTimeout(child.stdin.end.bind(child.stdin), 200); - } -}); - -child.on('close', function(c) { - assert(!c); - // make sure we got 3 throws, in the end. - var lastLine = stdout.trim().split(/\r?\n/).pop(); - assert.equal(lastLine, '> 3'); -}); diff --git a/test/simple/test-repl.js b/test/simple/test-repl.js deleted file mode 100644 index 69b9b54d1..000000000 --- a/test/simple/test-repl.js +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -common.globalCheck = false; - -var net = require('net'), - repl = require('repl'), - message = 'Read, Eval, Print Loop', - prompt_unix = 'node via Unix socket> ', - prompt_tcp = 'node via TCP socket> ', - prompt_multiline = '... ', - prompt_npm = 'npm should be run outside of the ' + - 'node repl, in your normal shell.\n' + - '(Press Control-D to exit.)\n', - expect_npm = prompt_npm + prompt_unix, - server_tcp, server_unix, client_tcp, client_unix, timer; - - -// absolute path to test/fixtures/a.js -var moduleFilename = require('path').join(common.fixturesDir, 'a'); - -console.error('repl test'); - -// function for REPL to run -invoke_me = function(arg) { - return 'invoked ' + arg; -}; - -function send_expect(list) { - if (list.length > 0) { - var cur = list.shift(); - - console.error('sending ' + JSON.stringify(cur.send)); - - cur.client.expect = cur.expect; - cur.client.list = list; - if (cur.send.length > 0) { - cur.client.write(cur.send + '\n'); - } - } -} - -function clean_up() { - client_tcp.end(); - client_unix.end(); - clearTimeout(timer); -} - -function error_test() { - // The other stuff is done so reuse unix socket - var read_buffer = ''; - client_unix.removeAllListeners('data'); - - client_unix.on('data', function(data) { - read_buffer += data.toString('ascii', 0, data.length); - console.error('Unix data: ' + JSON.stringify(read_buffer) + ', expecting ' + - (client_unix.expect.exec ? - client_unix.expect : - JSON.stringify(client_unix.expect))); - - if (read_buffer.indexOf(prompt_unix) !== -1) { - // if it's an exact match, then don't do the regexp - if (read_buffer !== client_unix.expect) { - var expect = client_unix.expect; - if (expect === prompt_multiline) - expect = /[\.]{3} /; - assert.ok(read_buffer.match(expect)); - console.error('match'); - } - read_buffer = ''; - if (client_unix.list && client_unix.list.length > 0) { - send_expect(client_unix.list); - } else { - console.error('End of Error test, running TCP test.'); - tcp_test(); - } - - } else if (read_buffer.indexOf(prompt_multiline) !== -1) { - // Check that you meant to send a multiline test - assert.strictEqual(prompt_multiline, client_unix.expect); - read_buffer = ''; - if (client_unix.list && client_unix.list.length > 0) { - send_expect(client_unix.list); - } else { - console.error('End of Error test, running TCP test.\n'); - tcp_test(); - } - - } else { - console.error('didn\'t see prompt yet, buffering.'); - } - }); - - send_expect([ - // Uncaught error throws and prints out - { client: client_unix, send: 'throw new Error(\'test error\');', - expect: /^Error: test error/ }, - // Common syntax error is treated as multiline command - { client: client_unix, send: 'function test_func() {', - expect: prompt_multiline }, - // You can recover with the .break command - { client: client_unix, send: '.break', - expect: prompt_unix }, - // But passing the same string to eval() should throw - { client: client_unix, send: 'eval("function test_func() {")', - expect: /^SyntaxError: Unexpected end of input/ }, - // Floating point numbers are not interpreted as REPL commands. - { client: client_unix, send: '.1234', - expect: '0.1234' }, - // Floating point expressions are not interpreted as REPL commands - { client: client_unix, send: '.1+.1', - expect: '0.2' }, - // Can parse valid JSON - { client: client_unix, send: 'JSON.parse(\'{"valid": "json"}\');', - expect: '{ valid: \'json\' }'}, - // invalid input to JSON.parse error is special case of syntax error, - // should throw - { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', - expect: /^SyntaxError: Unexpected token i/ }, - // end of input to JSON.parse error is special case of syntax error, - // should throw - { client: client_unix, send: 'JSON.parse(\'066\');', - expect: /^SyntaxError: Unexpected number/ }, - // should throw - { client: client_unix, send: 'JSON.parse(\'{\');', - expect: /^SyntaxError: Unexpected end of input/ }, - // invalid RegExps are a special case of syntax error, - // should throw - { client: client_unix, send: '/(/;', - expect: /^SyntaxError: Invalid regular expression\:/ }, - // invalid RegExp modifiers are a special case of syntax error, - // should throw (GH-4012) - { client: client_unix, send: 'new RegExp("foo", "wrong modifier");', - expect: /^SyntaxError: Invalid flags supplied to RegExp constructor/ }, - // strict mode syntax errors should be caught (GH-5178) - { client: client_unix, send: '(function() { "use strict"; return 0755; })()', - expect: /^SyntaxError: Octal literals are not allowed in strict mode/ }, - { client: client_unix, send: '(function() { "use strict"; return { p: 1, p: 2 }; })()', - expect: /^SyntaxError: Duplicate data property in object literal not allowed in strict mode/ }, - { client: client_unix, send: '(function(a, a, b) { "use strict"; return a + b + c; })()', - expect: /^SyntaxError: Strict mode function may not have duplicate parameter names/ }, - { client: client_unix, send: '(function() { "use strict"; with (this) {} })()', - expect: /^SyntaxError: Strict mode code may not include a with statement/ }, - { client: client_unix, send: '(function() { "use strict"; var x; delete x; })()', - expect: /^SyntaxError: Delete of an unqualified identifier in strict mode/ }, - { client: client_unix, send: '(function() { "use strict"; eval = 17; })()', - expect: /^SyntaxError: Unexpected eval or arguments in strict mode/ }, - { client: client_unix, send: '(function() { "use strict"; if (true){ function f() { } } })()', - expect: /^SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function/ }, - // Named functions can be used: - { client: client_unix, send: 'function blah() { return 1; }', - expect: prompt_unix }, - { client: client_unix, send: 'blah()', - expect: '1\n' + prompt_unix }, - // Functions should not evaluate twice (#2773) - { client: client_unix, send: 'var I = [1,2,3,function() {}]; I.pop()', - expect: '[Function]' }, - // Multiline object - { client: client_unix, send: '{ a: ', - expect: prompt_multiline }, - { client: client_unix, send: '1 }', - expect: '{ a: 1 }' }, - // Multiline anonymous function with comment - { client: client_unix, send: '(function () {', - expect: prompt_multiline }, - { client: client_unix, send: '// blah', - expect: prompt_multiline }, - { client: client_unix, send: 'return 1;', - expect: prompt_multiline }, - { client: client_unix, send: '})()', - expect: '1' }, - // npm prompt error message - { client: client_unix, send: 'npm install foobar', - expect: expect_npm }, - { client: client_unix, send: '(function () {\n\nreturn 1;\n})()', - expect: '1' }, - { client: client_unix, send: '{\n\na: 1\n}', - expect: '{ a: 1 }' }, - { client: client_unix, send: 'url.format("http://google.com")', - expect: 'http://google.com/' }, - { client: client_unix, send: 'var path = 42; path', - expect: '42' } - ]); -} - -function tcp_test() { - server_tcp = net.createServer(function(socket) { - assert.strictEqual(server_tcp, socket.server); - - socket.on('end', function() { - socket.end(); - }); - - repl.start(prompt_tcp, socket); - }); - - server_tcp.listen(common.PORT, function() { - var read_buffer = ''; - - client_tcp = net.createConnection(common.PORT); - - client_tcp.on('connect', function() { - assert.equal(true, client_tcp.readable); - assert.equal(true, client_tcp.writable); - - send_expect([ - { client: client_tcp, send: '', - expect: prompt_tcp }, - { client: client_tcp, send: 'invoke_me(333)', - expect: ('\'' + 'invoked 333' + '\'\n' + prompt_tcp) }, - { client: client_tcp, send: 'a += 1', - expect: ('12346' + '\n' + prompt_tcp) }, - { client: client_tcp, - send: 'require(' + JSON.stringify(moduleFilename) + ').number', - expect: ('42' + '\n' + prompt_tcp) } - ]); - }); - - client_tcp.on('data', function(data) { - read_buffer += data.toString('ascii', 0, data.length); - console.error('TCP data: ' + JSON.stringify(read_buffer) + - ', expecting ' + JSON.stringify(client_tcp.expect)); - if (read_buffer.indexOf(prompt_tcp) !== -1) { - assert.strictEqual(client_tcp.expect, read_buffer); - console.error('match'); - read_buffer = ''; - if (client_tcp.list && client_tcp.list.length > 0) { - send_expect(client_tcp.list); - } else { - console.error('End of TCP test.\n'); - clean_up(); - } - } else { - console.error('didn\'t see prompt yet, buffering'); - } - }); - - client_tcp.on('error', function(e) { - throw e; - }); - - client_tcp.on('close', function() { - server_tcp.close(); - }); - }); - -} - -function unix_test() { - server_unix = net.createServer(function(socket) { - assert.strictEqual(server_unix, socket.server); - - socket.on('end', function() { - socket.end(); - }); - - repl.start({ - prompt: prompt_unix, - input: socket, - output: socket, - useGlobal: true - }).context.message = message; - }); - - server_unix.on('listening', function() { - var read_buffer = ''; - - client_unix = net.createConnection(common.PIPE); - - client_unix.on('connect', function() { - assert.equal(true, client_unix.readable); - assert.equal(true, client_unix.writable); - - send_expect([ - { client: client_unix, send: '', - expect: prompt_unix }, - { client: client_unix, send: 'message', - expect: ('\'' + message + '\'\n' + prompt_unix) }, - { client: client_unix, send: 'invoke_me(987)', - expect: ('\'' + 'invoked 987' + '\'\n' + prompt_unix) }, - { client: client_unix, send: 'a = 12345', - expect: ('12345' + '\n' + prompt_unix) }, - { client: client_unix, send: '{a:1}', - expect: ('{ a: 1 }' + '\n' + prompt_unix) } - ]); - }); - - client_unix.on('data', function(data) { - read_buffer += data.toString('ascii', 0, data.length); - console.error('Unix data: ' + JSON.stringify(read_buffer) + - ', expecting ' + JSON.stringify(client_unix.expect)); - if (read_buffer.indexOf(prompt_unix) !== -1) { - assert.strictEqual(client_unix.expect, read_buffer); - console.error('match'); - read_buffer = ''; - if (client_unix.list && client_unix.list.length > 0) { - send_expect(client_unix.list); - } else { - console.error('End of Unix test, running Error test.\n'); - process.nextTick(error_test); - } - } else { - console.error('didn\'t see prompt yet, buffering.'); - } - }); - - client_unix.on('error', function(e) { - throw e; - }); - - client_unix.on('close', function() { - server_unix.close(); - }); - }); - - server_unix.listen(common.PIPE); -} - -unix_test(); - -timer = setTimeout(function() { - assert.fail('Timeout'); -}, 5000); diff --git a/test/simple/test-require-cache-without-stat.js b/test/simple/test-require-cache-without-stat.js deleted file mode 100644 index c2c6c0655..000000000 --- a/test/simple/test-require-cache-without-stat.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// We've experienced a regression where the module loader stats a bunch of -// directories on require() even if it's been called before. The require() -// should caching the request. -var common = require('../common'); -var fs = require('fs'); -var assert = require('assert'); - -var counter = 0; - -// Switch out the two stat implementations so that they increase a counter -// each time they are called. - -var _statSync = fs.statSync; -var _stat = fs.stat; - -fs.statSync = function() { - counter++; - return _statSync.apply(this, arguments); -}; - -fs.stat = function() { - counter++; - return _stat.apply(this, arguments); -}; - -// Load the module 'a' and 'http' once. It should become cached. -require(common.fixturesDir + '/a'); -require('../fixtures/a.js'); -require('./../fixtures/a.js'); -require('http'); - -console.log('counterBefore = %d', counter); -var counterBefore = counter; - -// Now load the module a bunch of times with equivalent paths. -// stat should not be called. -for (var i = 0; i < 100; i++) { - require(common.fixturesDir + '/a'); - require('../fixtures/a.js'); - require('./../fixtures/a.js'); -} - -// Do the same with a built-in module -for (var i = 0; i < 100; i++) { - require('http'); -} - -console.log('counterAfter = %d', counter); -var counterAfter = counter; - -assert.equal(counterBefore, counterAfter); diff --git a/test/simple/test-require-cache.js b/test/simple/test-require-cache.js deleted file mode 100644 index 2f812044a..000000000 --- a/test/simple/test-require-cache.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -(function testInjectFakeModule() { - var relativePath = '../fixtures/semicolon'; - var absolutePath = require.resolve(relativePath); - var fakeModule = {}; - - require.cache[absolutePath] = {exports: fakeModule}; - - assert.strictEqual(require(relativePath), fakeModule); -})(); - - -(function testInjectFakeNativeModule() { - var relativePath = 'fs'; - var fakeModule = {}; - - require.cache[relativePath] = {exports: fakeModule}; - - assert.strictEqual(require(relativePath), fakeModule); -})(); diff --git a/test/simple/test-require-exceptions.js b/test/simple/test-require-exceptions.js deleted file mode 100644 index 307e3e2f3..000000000 --- a/test/simple/test-require-exceptions.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// A module with an error in it should throw -assert.throws(function() { - require(common.fixturesDir + '/throws_error'); -}); - -// Requiring the same module again should throw as well -assert.throws(function() { - require(common.fixturesDir + '/throws_error'); -}); - -// Requiring a module that does not exist should throw an -// error with its `code` set to MODULE_NOT_FOUND -assert.throws(function() { - require(common.fixturesDir + '/DOES_NOT_EXIST'); -}, function(e) { - assert.equal('MODULE_NOT_FOUND', e.code); - return true; -}); diff --git a/test/simple/test-require-extensions-main.js b/test/simple/test-require-extensions-main.js deleted file mode 100644 index 032f2eb2c..000000000 --- a/test/simple/test-require-extensions-main.js +++ /dev/null @@ -1,4 +0,0 @@ -var common = require('../common'); -var assert = require('assert'); - -require(common.fixturesDir + '/require-bin/bin/req.js'); diff --git a/test/simple/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/simple/test-require-extensions-same-filename-as-dir-trailing-slash.js deleted file mode 100644 index 6469d14ff..000000000 --- a/test/simple/test-require-extensions-same-filename-as-dir-trailing-slash.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var content = require(common.fixturesDir + - '/json-with-directory-name-module/module-stub/one-trailing-slash/two/three.js'); - -assert.notEqual(content.rocko, 'artischocko'); -assert.equal(content, 'hello from module-stub!'); diff --git a/test/simple/test-require-extensions-same-filename-as-dir.js b/test/simple/test-require-extensions-same-filename-as-dir.js deleted file mode 100644 index fbfba3b9b..000000000 --- a/test/simple/test-require-extensions-same-filename-as-dir.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var content = require(common.fixturesDir + - '/json-with-directory-name-module/module-stub/one/two/three.js'); - -assert.notEqual(content.rocko, 'artischocko'); -assert.equal(content, 'hello from module-stub!'); diff --git a/test/simple/test-require-json.js b/test/simple/test-require-json.js deleted file mode 100644 index 59b1e3d61..000000000 --- a/test/simple/test-require-json.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); - -try { - require('../fixtures/invalid.json'); -} catch (err) { - var re = /test[\/\\]fixtures[\/\\]invalid.json: Unexpected string/; - var i = err.message.match(re); - assert(null !== i, 'require() json error should include path'); -} diff --git a/test/simple/test-require-resolve.js b/test/simple/test-require-resolve.js deleted file mode 100644 index 490deae68..000000000 --- a/test/simple/test-require-resolve.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var fixturesDir = common.fixturesDir; -var assert = require('assert'); -var path = require('path'); - -assert.equal( - path.join(__dirname, '../fixtures/a.js').toLowerCase(), - require.resolve('../fixtures/a').toLowerCase()); -assert.equal( - path.join(fixturesDir, 'a.js').toLowerCase(), - require.resolve(path.join(fixturesDir, 'a')).toLowerCase()); -assert.equal( - path.join(fixturesDir, 'nested-index', 'one', 'index.js').toLowerCase(), - require.resolve('../fixtures/nested-index/one').toLowerCase()); -assert.equal('path', require.resolve('path')); - -console.log('ok'); diff --git a/test/simple/test-setproctitle.js b/test/simple/test-setproctitle.js deleted file mode 100644 index 6373af4cd..000000000 --- a/test/simple/test-setproctitle.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Original test written by Jakub Lekstan - -// FIXME add sunos support -if ('linux freebsd darwin'.indexOf(process.platform) === -1) { - console.error('Skipping test, platform not supported.'); - process.exit(); -} - -var common = require('../common'); -var assert = require('assert'); -var exec = require('child_process').exec; - -// The title shouldn't be too long; libuv's uv_set_process_title() out of -// security considerations no longer overwrites envp, only argv, so the -// maximum title length is possibly quite short. -var title = 'testme'; - -assert.notEqual(process.title, title); -process.title = title; -assert.equal(process.title, title); - -exec('ps -p ' + process.pid + ' -o args=', function(error, stdout, stderr) { - assert.equal(error, null); - assert.equal(stderr, ''); - - // freebsd always add ' (procname)' to the process title - if (process.platform === 'freebsd') title += ' (node)'; - - // omitting trailing whitespace and \n - assert.equal(stdout.replace(/\s+$/, ''), title); -}); diff --git a/test/simple/test-sigint-infinite-loop.js b/test/simple/test-sigint-infinite-loop.js deleted file mode 100644 index 4ff274584..000000000 --- a/test/simple/test-sigint-infinite-loop.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -// This test is to assert that we can SIGINT a script which loops forever. -// Ref(http): -// groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f -var common = require('../common'); -var assert = require('assert'); -var spawn = require('child_process').spawn; - -console.log('start'); - -var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); - -var sentKill = false; -var gotChildExit = true; - -c.stdout.on('data', function(s) { - // Prevent race condition: - // Wait for the first bit of output from the child process - // so that we're sure that it's in the V8 event loop and not - // just in the startup phase of execution. - if (!sentKill) { - c.kill('SIGINT'); - console.log('SIGINT infinite-loop.js'); - sentKill = true; - } -}); - -c.on('exit', function(code) { - assert.ok(code !== 0); - console.log('killed infinite-loop.js'); - gotChildExit = true; -}); - -process.on('exit', function() { - assert.ok(sentKill); - assert.ok(gotChildExit); -}); - diff --git a/test/simple/test-signal-handler.js b/test/simple/test-signal-handler.js deleted file mode 100644 index 5531e2f55..000000000 --- a/test/simple/test-signal-handler.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// SIGUSR1 and SIGHUP are not supported on Windows -if (process.platform === 'win32') { - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); - -console.log('process.pid: ' + process.pid); - -var first = 0, - second = 0; - -var sighup = false; - -process.on('SIGUSR1', function() { - console.log('Interrupted by SIGUSR1'); - first += 1; -}); - -process.on('SIGUSR1', function() { - second += 1; - setTimeout(function() { - console.log('End.'); - process.exit(0); - }, 5); -}); - -var i = 0; -setInterval(function() { - console.log('running process...' + ++i); - - if (i == 5) { - process.kill(process.pid, 'SIGUSR1'); - } -}, 1); - -// Test on condition where a watcher for SIGNAL -// has been previously registered, and `process.listeners(SIGNAL).length === 1` -process.on('SIGHUP', function() {}); -process.removeAllListeners('SIGHUP'); -process.on('SIGHUP', function() { sighup = true }); -process.kill(process.pid, 'SIGHUP'); - -process.on('exit', function() { - assert.equal(1, first); - assert.equal(1, second); - assert.equal(true, sighup); -}); diff --git a/test/simple/test-signal-safety.js b/test/simple/test-signal-safety.js deleted file mode 100644 index 4707b634d..000000000 --- a/test/simple/test-signal-safety.js +++ /dev/null @@ -1,11 +0,0 @@ -var common = require('../common.js'); -var assert = require('assert'); -var Signal = process.binding('signal_wrap').Signal; - -// Test Signal `this` safety -// https://github.com/joyent/node/issues/6690 -assert.throws(function() { - var s = new Signal(); - var nots = { start: s.start }; - nots.start(9); -}, TypeError); diff --git a/test/simple/test-signal-unregister.js b/test/simple/test-signal-unregister.js deleted file mode 100644 index d65e0a0d9..000000000 --- a/test/simple/test-signal-unregister.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); - -var childKilled = false, done = false, - spawn = require('child_process').spawn, - util = require('util'), - child; - -var join = require('path').join; - -child = spawn(process.argv[0], [join(common.fixturesDir, 'should_exit.js')]); -child.on('exit', function() { - if (!done) childKilled = true; -}); - -setTimeout(function() { - console.log('Sending SIGINT'); - child.kill('SIGINT'); - setTimeout(function() { - console.log('Chance has been given to die'); - done = true; - if (!childKilled) { - // Cleanup - console.log('Child did not die on SIGINT, sending SIGTERM'); - child.kill('SIGTERM'); - } - }, 200); -}, 200); - -process.on('exit', function() { - assert.ok(childKilled); -}); diff --git a/test/simple/test-smalloc.js b/test/simple/test-smalloc.js deleted file mode 100644 index 198b5c7f5..000000000 --- a/test/simple/test-smalloc.js +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var os = require('os'); - -// first grab js api's -var smalloc = require('smalloc'); -var alloc = smalloc.alloc; -var dispose = smalloc.dispose; -var copyOnto = smalloc.copyOnto; -var kMaxLength = smalloc.kMaxLength; -var Types = smalloc.Types; -// sliceOnto is volatile and cannot be exposed to users. -var sliceOnto = process.binding('smalloc').sliceOnto; - - -// verify allocation - -var b = alloc(5, {}); -assert.ok(typeof b === 'object'); -for (var i = 0; i < 5; i++) - assert.ok(b[i] !== undefined); - - -var b = {}; -var c = alloc(5, b); -assert.equal(b, c); -assert.deepEqual(b, c); - - -var b = alloc(5, {}); -var c = {}; -c._data = sliceOnto(b, c, 0, 5); -assert.ok(typeof c._data === 'object'); -assert.equal(b, c._data); -assert.deepEqual(b, c._data); - - -// verify writes - -var b = alloc(5, {}); -for (var i = 0; i < 5; i++) - b[i] = i; -for (var i = 0; i < 5; i++) - assert.equal(b[i], i); - - -var b = alloc(1, Types.Uint8); -b[0] = 256; -assert.equal(b[0], 0); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Int8); -b[0] = 128; -assert.equal(b[0], -128); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Uint16); -b[0] = 65536; -assert.equal(b[0], 0); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Int16); -b[0] = 32768; -assert.equal(b[0], -32768); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Uint32); -b[0] = 4294967296; -assert.equal(b[0], 0); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Int32); -b[0] = 2147483648; -assert.equal(b[0], -2147483648); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Float); -b[0] = 0.1111111111111111; -assert.equal(b[0], 0.1111111119389534); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Double); -b[0] = 0.1111111111111111; -assert.equal(b[0], 0.1111111111111111); -assert.equal(b[1], undefined); - - -var b = alloc(1, Types.Uint8Clamped); -b[0] = 300; -assert.equal(b[0], 255); -assert.equal(b[1], undefined); - - -var b = alloc(6, {}); -var c0 = {}; -var c1 = {}; -c0._data = sliceOnto(b, c0, 0, 3); -c1._data = sliceOnto(b, c1, 3, 6); -for (var i = 0; i < 3; i++) { - c0[i] = i; - c1[i] = i + 3; -} -for (var i = 0; i < 3; i++) - assert.equal(b[i], i); -for (var i = 3; i < 6; i++) - assert.equal(b[i], i); - - -var a = alloc(6, {}); -var b = alloc(6, {}); -var c = alloc(12, {}); -for (var i = 0; i < 6; i++) { - a[i] = i; - b[i] = i * 2; -} -copyOnto(a, 0, c, 0, 6); -copyOnto(b, 0, c, 6, 6); -for (var i = 0; i < 6; i++) { - assert.equal(c[i], i); - assert.equal(c[i + 6], i * 2); -} - - -var b = alloc(1, Types.Double); -var c = alloc(2, Types.Uint32); -if (os.endianness() === 'LE') { - c[0] = 2576980378; - c[1] = 1069128089; -} else { - c[0] = 1069128089; - c[1] = 2576980378; -} -copyOnto(c, 0, b, 0, 2); -assert.equal(b[0], 0.1); - -var b = alloc(1, Types.Uint16); -var c = alloc(2, Types.Uint8); -c[0] = c[1] = 0xff; -copyOnto(c, 0, b, 0, 2); -assert.equal(b[0], 0xffff); - -var b = alloc(2, Types.Uint8); -var c = alloc(1, Types.Uint16); -c[0] = 0xffff; -copyOnto(c, 0, b, 0, 1); -assert.equal(b[0], 0xff); -assert.equal(b[1], 0xff); - - - -// verify checking external if has external memory - -// check objects -var b = {}; -assert.ok(!smalloc.hasExternalData(b)); -alloc(1, b); -assert.ok(smalloc.hasExternalData(b)); -var f = function() { }; -alloc(1, f); -assert.ok(smalloc.hasExternalData(f)); - -// and non-objects -assert.ok(!smalloc.hasExternalData(true)); -assert.ok(!smalloc.hasExternalData(1)); -assert.ok(!smalloc.hasExternalData('string')); -assert.ok(!smalloc.hasExternalData(null)); -assert.ok(!smalloc.hasExternalData()); - - -// verify alloc throws properly - -// arrays are not supported -assert.throws(function() { - alloc(0, []); -}, TypeError); - - -// no allocations larger than kMaxLength -assert.throws(function() { - alloc(kMaxLength + 1); -}, RangeError); - - -// properly convert to uint32 before checking overflow -assert.throws(function() { - alloc(-1); -}, RangeError); - - -// no allocating on what's been allocated -assert.throws(function() { - alloc(1, alloc(1)); -}, TypeError); - - -// throw for values passed that are not objects -assert.throws(function() { - alloc(1, 'a'); -}, TypeError); -assert.throws(function() { - alloc(1, true); -}, TypeError); -assert.throws(function() { - alloc(1, null); -}, TypeError); - - -// should not throw allocating to most objects -alloc(1, function() { }); -alloc(1, /abc/); -alloc(1, new Date()); - - -// range check on external array enumeration -assert.throws(function() { - alloc(1, 0); -}, TypeError); -assert.throws(function() { - alloc(1, 10); -}, TypeError); - -// very copyOnto throws properly - -// source must have data -assert.throws(function() { - copyOnto({}, 0, alloc(1), 0, 0); -}, Error); - - -// dest must have data -assert.throws(function() { - copyOnto(alloc(1), 0, {}, 0, 0); -}, Error); - - -// copyLength <= sourceLength -assert.throws(function() { - copyOnto(alloc(1), 0, alloc(3), 0, 2); -}, RangeError); - - -// copyLength <= destLength -assert.throws(function() { - copyOnto(alloc(3), 0, alloc(1), 0, 2); -}, RangeError); - - -// sourceStart <= sourceLength -assert.throws(function() { - copyOnto(alloc(1), 3, alloc(1), 0, 1); -}, RangeError); - - -// destStart <= destLength -assert.throws(function() { - copyOnto(alloc(1), 0, alloc(1), 3, 1); -}, RangeError); - - -// sourceStart + copyLength <= sourceLength -assert.throws(function() { - copyOnto(alloc(3), 1, alloc(3), 0, 3); -}, RangeError); - - -// destStart + copyLength <= destLength -assert.throws(function() { - copyOnto(alloc(3), 0, alloc(3), 1, 3); -}, RangeError); - - -// copy_length * array_size <= dest_length -assert.throws(function() { - copyOnto(alloc(2, Types.Double), 0, alloc(2, Types.Uint32), 0, 2); -}, RangeError); - - -// test disposal -var b = alloc(5, {}); -dispose(b); -for (var i = 0; i < 5; i++) - assert.equal(b[i], undefined); - - -// verify dispose throws properly - -// only allow object to be passed to dispose -assert.throws(function() { - smalloc.dispose(null); -}); - - -// can't dispose a Buffer -assert.throws(function() { - smalloc.dispose(new Buffer()); -}); - -assert.throws(function() { - smalloc.dispose(new Uint8Array(new ArrayBuffer(1))); -}); - -assert.throws(function() { - smalloc.dispose({}); -}); diff --git a/test/simple/test-socket-write-after-fin-error.js b/test/simple/test-socket-write-after-fin-error.js deleted file mode 100644 index 123557417..000000000 --- a/test/simple/test-socket-write-after-fin-error.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// This is similar to simple/test-socket-write-after-fin, except that -// we don't set allowHalfOpen. Then we write after the client has sent -// a FIN, and this is an error. However, the standard "write after end" -// message is too vague, and doesn't actually tell you what happens. - -var net = require('net'); -var serverData = ''; -var gotServerEnd = false; -var clientData = ''; -var gotClientEnd = false; -var gotServerError = false; - -var server = net.createServer(function(sock) { - sock.setEncoding('utf8'); - sock.on('error', function(er) { - console.error(er.code + ': ' + er.message); - gotServerError = er; - }); - - sock.on('data', function(c) { - serverData += c; - }); - sock.on('end', function() { - gotServerEnd = true - sock.write(serverData); - sock.end(); - }); - server.close(); -}); -server.listen(common.PORT); - -var sock = net.connect(common.PORT); -sock.setEncoding('utf8'); -sock.on('data', function(c) { - clientData += c; -}); - -sock.on('end', function() { - gotClientEnd = true; -}); - -process.on('exit', function() { - assert.equal(clientData, ''); - assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); - assert(gotClientEnd); - assert(gotServerEnd); - assert(gotServerError); - assert.equal(gotServerError.code, 'EPIPE'); - assert.notEqual(gotServerError.message, 'write after end'); - console.log('ok'); -}); - -sock.write('hello1'); -sock.write('hello2'); -sock.write('hello3\n'); -sock.end('THUNDERMUSCLE!'); diff --git a/test/simple/test-socket-write-after-fin.js b/test/simple/test-socket-write-after-fin.js deleted file mode 100644 index 88d780b81..000000000 --- a/test/simple/test-socket-write-after-fin.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var serverData = ''; -var gotServerEnd = false; -var clientData = ''; -var gotClientEnd = false; - -var server = net.createServer({ allowHalfOpen: true }, function(sock) { - sock.setEncoding('utf8'); - sock.on('data', function(c) { - serverData += c; - }); - sock.on('end', function() { - gotServerEnd = true - sock.end(serverData); - server.close(); - }); -}); -server.listen(common.PORT); - -var sock = net.connect(common.PORT); -sock.setEncoding('utf8'); -sock.on('data', function(c) { - clientData += c; -}); - -sock.on('end', function() { - gotClientEnd = true; -}); - -process.on('exit', function() { - assert.equal(serverData, clientData); - assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); - assert(gotClientEnd); - assert(gotServerEnd); - console.log('ok'); -}); - -sock.write('hello1'); -sock.write('hello2'); -sock.write('hello3\n'); -sock.end('THUNDERMUSCLE!'); diff --git a/test/simple/test-stdin-child-proc.js b/test/simple/test-stdin-child-proc.js deleted file mode 100644 index 6a4ea9473..000000000 --- a/test/simple/test-stdin-child-proc.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This tests that pausing and resuming stdin does not hang and timeout -// when done in a child process. See test/simple/test-stdin-pause-resume.js -var common = require('../common'); -var child_process = require('child_process'); -var path = require('path'); -child_process.spawn(process.execPath, - [path.resolve(__dirname, 'test-stdin-pause-resume.js')]); diff --git a/test/simple/test-stdin-from-file.js b/test/simple/test-stdin-from-file.js deleted file mode 100644 index 617b9037d..000000000 --- a/test/simple/test-stdin-from-file.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var join = require('path').join; -var childProccess = require('child_process'); -var fs = require('fs'); - -var stdoutScript = join(common.fixturesDir, 'echo-close-check.js'); -var tmpFile = join(common.fixturesDir, 'stdin.txt'); - -var cmd = '"' + process.argv[0] + '" "' + stdoutScript + '" < "' + - tmpFile + '"'; - -var string = 'abc\nümlaut.\nsomething else\n' + - '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,' + - '疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、' + - '云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + - '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + - '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + - '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' + - '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + - '采用封建制和郡县制并存的制度,' + - '它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + - '有效的改善了岭南地区落后的政治、##济现状。\n'; - - -console.log(cmd + '\n\n'); - -try { - fs.unlinkSync(tmpFile); -} catch (e) {} - -fs.writeFileSync(tmpFile, string); - -childProccess.exec(cmd, function(err, stdout, stderr) { - fs.unlinkSync(tmpFile); - - if (err) throw err; - console.log(stdout); - assert.equal(stdout, 'hello world\r\n' + string); - assert.equal('', stderr); -}); diff --git a/test/simple/test-stdin-hang.js b/test/simple/test-stdin-hang.js deleted file mode 100644 index 1edbf8c25..000000000 --- a/test/simple/test-stdin-hang.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -// This test *only* verifies that invoking the stdin getter does not -// cause node to hang indefinitely. -// If it does, then the test-runner will nuke it. - -// invoke the getter. -process.stdin; - -console.error('Should exit normally now.'); diff --git a/test/simple/test-stdin-pause-resume-sync.js b/test/simple/test-stdin-pause-resume-sync.js deleted file mode 100644 index 0e202a306..000000000 --- a/test/simple/test-stdin-pause-resume-sync.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -console.error('before opening stdin'); -process.stdin.resume(); -console.error('stdin opened'); -console.error('pausing stdin'); -process.stdin.pause(); -console.error('opening again'); -process.stdin.resume(); -console.error('pausing again'); -process.stdin.pause(); -console.error('should exit now'); diff --git a/test/simple/test-stdin-pause-resume.js b/test/simple/test-stdin-pause-resume.js deleted file mode 100644 index fed5d6653..000000000 --- a/test/simple/test-stdin-pause-resume.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -console.error('before opening stdin'); -process.stdin.resume(); -console.error('stdin opened'); -setTimeout(function() { - console.error('pausing stdin'); - process.stdin.pause(); - setTimeout(function() { - console.error('opening again'); - process.stdin.resume(); - setTimeout(function() { - console.error('pausing again'); - process.stdin.pause(); - console.error('should exit now'); - }, 1); - }, 1); -}, 1); diff --git a/test/simple/test-stdin-pipe-resume.js b/test/simple/test-stdin-pipe-resume.js deleted file mode 100644 index 163d8369c..000000000 --- a/test/simple/test-stdin-pipe-resume.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This tests that piping stdin will cause it to resume() as well. -var common = require('../common'); -var assert = require('assert'); - -if (process.argv[2] === 'child') { - process.stdin.pipe(process.stdout); -} else { - var spawn = require('child_process').spawn; - var buffers = []; - var child = spawn(process.execPath, [__filename, 'child']); - child.stdout.on('data', function(c) { - buffers.push(c); - }); - child.stdout.on('close', function() { - var b = Buffer.concat(buffers).toString(); - assert.equal(b, 'Hello, world\n'); - console.log('ok'); - }); - child.stdin.write('Hel'); - child.stdin.write('lo,'); - child.stdin.write(' wo'); - setTimeout(function() { - child.stdin.write('rld\n'); - child.stdin.end(); - }, 10); -} - diff --git a/test/simple/test-stdin-resume-pause.js b/test/simple/test-stdin-resume-pause.js deleted file mode 100644 index 2d2af2fc6..000000000 --- a/test/simple/test-stdin-resume-pause.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -process.stdin.resume(); -process.stdin.pause(); diff --git a/test/simple/test-stdin-script-child.js b/test/simple/test-stdin-script-child.js deleted file mode 100644 index e940c3c3f..000000000 --- a/test/simple/test-stdin-script-child.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var spawn = require('child_process').spawn; -var child = spawn(process.execPath, [], { - env: { - NODE_DEBUG: process.argv[2] - } -}); -var wanted = child.pid + '\n'; -var found = ''; - -child.stdout.setEncoding('utf8'); -child.stdout.on('data', function(c) { - found += c; -}); - -child.stderr.setEncoding('utf8'); -child.stderr.on('data', function(c) { - console.error('> ' + c.trim().split(/\n/).join('\n> ')); -}); - -child.on('close', function(c) { - assert(!c); - assert.equal(found, wanted); - console.log('ok'); -}); - -setTimeout(function() { - child.stdin.end('console.log(process.pid)'); -}); diff --git a/test/simple/test-stdio-readable-writable.js b/test/simple/test-stdio-readable-writable.js deleted file mode 100644 index 5123f9688..000000000 --- a/test/simple/test-stdio-readable-writable.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -assert(process.stdout.writable); -assert(!process.stdout.readable); - -assert(process.stderr.writable); -assert(!process.stderr.readable); - -assert(!process.stdin.writable); -assert(process.stdin.readable); diff --git a/test/simple/test-stdout-cannot-be-closed-child-process-pipe.js b/test/simple/test-stdout-cannot-be-closed-child-process-pipe.js deleted file mode 100644 index 2e79c5af1..000000000 --- a/test/simple/test-stdout-cannot-be-closed-child-process-pipe.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -if (process.argv[2] === 'child') - process.stdout.end('foo'); -else - parent(); - -function parent() { - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child']); - var out = ''; - var err = ''; - - child.stdout.setEncoding('utf8'); - child.stderr.setEncoding('utf8'); - - child.stdout.on('data', function(c) { - out += c; - }); - child.stderr.on('data', function(c) { - err += c; - }); - - child.on('close', function(code, signal) { - assert(code); - assert.equal(out, 'foo'); - assert(/process\.stdout cannot be closed/.test(err)); - console.log('ok'); - }); -} diff --git a/test/simple/test-stdout-close-catch.js b/test/simple/test-stdout-close-catch.js deleted file mode 100644 index f517a6cbe..000000000 --- a/test/simple/test-stdout-close-catch.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var child_process = require('child_process'); -var fs = require('fs'); - -var testScript = path.join(common.fixturesDir, 'catch-stdout-error.js'); - -var cmd = JSON.stringify(process.execPath) + ' ' + - JSON.stringify(testScript) + ' | ' + - JSON.stringify(process.execPath) + ' ' + - '-pe "process.exit(1);"'; - -var child = child_process.exec(cmd); -var output = ''; -var outputExpect = { 'code': 'EPIPE', - 'errno': 'EPIPE', - 'syscall': 'write' }; - -child.stderr.on('data', function(c) { - output += c; -}); - -child.on('close', function(code) { - try { - output = JSON.parse(output); - } catch (er) { - console.error(output); - process.exit(1); - } - - assert.deepEqual(output, outputExpect); - console.log('ok'); -}); diff --git a/test/simple/test-stdout-close-unref.js b/test/simple/test-stdout-close-unref.js deleted file mode 100644 index f8cbc7e4b..000000000 --- a/test/simple/test-stdout-close-unref.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); - -var errs = 0; - -process.stdin.resume(); -process.stdin._handle.close(); -process.stdin._handle.unref(); // Should not segfault. -process.stdin.on('error', function(err) { - errs++; -}); - -process.on('exit', function() { - assert.strictEqual(errs, 1); -}); diff --git a/test/simple/test-stdout-stderr-reading.js b/test/simple/test-stdout-stderr-reading.js deleted file mode 100644 index 5b67a0d06..000000000 --- a/test/simple/test-stdout-stderr-reading.js +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// verify that stdout is never read from. -var net = require('net'); -var read = net.Socket.prototype.read; - -net.Socket.prototype.read = function() { - if (this.fd === 1) - throw new Error('reading from stdout!'); - if (this.fd === 2) - throw new Error('reading from stderr!'); - return read.apply(this, arguments); -}; - -if (process.argv[2] === 'child') - child(); -else - parent(); - -function parent() { - var spawn = require('child_process').spawn; - var node = process.execPath; - var closes = 0; - - var c1 = spawn(node, [__filename, 'child']); - var c1out = ''; - c1.stdout.setEncoding('utf8'); - c1.stdout.on('data', function(chunk) { - c1out += chunk; - }); - c1.stderr.setEncoding('utf8'); - c1.stderr.on('data', function(chunk) { - console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); - }); - c1.on('close', function(code, signal) { - closes++; - assert(!code); - assert(!signal); - assert.equal(c1out, 'ok\n'); - console.log('ok'); - }); - - var c2 = spawn(node, ['-e', 'console.log("ok")']); - var c2out = ''; - c2.stdout.setEncoding('utf8'); - c2.stdout.on('data', function(chunk) { - c2out += chunk; - }); - c1.stderr.setEncoding('utf8'); - c1.stderr.on('data', function(chunk) { - console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); - }); - c2.on('close', function(code, signal) { - closes++; - assert(!code); - assert(!signal); - assert.equal(c2out, 'ok\n'); - console.log('ok'); - }); - - process.on('exit', function() { - assert.equal(closes, 2, 'saw both closes'); - }); -} - -function child() { - // should not be reading *ever* in here. - net.Socket.prototype.read = function() { - throw new Error('no reading allowed in child'); - }; - console.log('ok'); -} diff --git a/test/simple/test-stdout-to-file.js b/test/simple/test-stdout-to-file.js deleted file mode 100644 index 94181ef81..000000000 --- a/test/simple/test-stdout-to-file.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var childProccess = require('child_process'); -var fs = require('fs'); - -var scriptString = path.join(common.fixturesDir, 'print-chars.js'); -var scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js'); -var tmpFile = path.join(common.tmpDir, 'stdout.txt'); - -function test(size, useBuffer, cb) { - var cmd = '"' + process.argv[0] + '"' + - ' ' + - '"' + (useBuffer ? scriptBuffer : scriptString) + '"' + - ' ' + - size + - ' > ' + - '"' + tmpFile + '"'; - - try { - fs.unlinkSync(tmpFile); - } catch (e) {} - - common.print(size + ' chars to ' + tmpFile + '...'); - - childProccess.exec(cmd, function(err) { - if (err) throw err; - - console.log('done!'); - - var stat = fs.statSync(tmpFile); - - console.log(tmpFile + ' has ' + stat.size + ' bytes'); - - assert.equal(size, stat.size); - fs.unlinkSync(tmpFile); - - cb(); - }); -} - -var finished = false; -test(1024 * 1024, false, function() { - console.log('Done printing with string'); - test(1024 * 1024, true, function() { - console.log('Done printing with buffer'); - finished = true; - }); -}); - -process.on('exit', function() { - assert.ok(finished); -}); diff --git a/test/simple/test-stream-big-packet.js b/test/simple/test-stream-big-packet.js deleted file mode 100644 index 9ec29ca0d..000000000 --- a/test/simple/test-stream-big-packet.js +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var stream = require('stream'); - -var passed = false; - -function PassThrough () { - stream.Transform.call(this); -}; -util.inherits(PassThrough, stream.Transform); -PassThrough.prototype._transform = function (chunk, encoding, done) { - this.push(chunk); - done(); -}; - -function TestStream () { - stream.Transform.call(this); -}; -util.inherits(TestStream, stream.Transform); -TestStream.prototype._transform = function (chunk, encoding, done) { - if (!passed) { - // Char 'a' only exists in the last write - passed = chunk.toString().indexOf('a') >= 0; - } - done(); -}; - -var s1 = new PassThrough(); -var s2 = new PassThrough(); -var s3 = new TestStream(); -s1.pipe(s3); -// Don't let s2 auto close which may close s3 -s2.pipe(s3, {end: false}); - -// We must write a buffer larger than highWaterMark -var big = new Buffer(s1._writableState.highWaterMark + 1); -big.fill('x'); - -// Since big is larger than highWaterMark, it will be buffered internally. -assert(!s1.write(big)); -// 'tiny' is small enough to pass through internal buffer. -assert(s2.write('tiny')); - -// Write some small data in next IO loop, which will never be written to s3 -// Because 'drain' event is not emitted from s1 and s1 is still paused -setImmediate(s1.write.bind(s1), 'later'); - -// Assert after two IO loops when all operations have been done. -process.on('exit', function () { - assert(passed, 'Large buffer is not handled properly by Writable Stream'); -}); diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js deleted file mode 100644 index e3787e441..000000000 --- a/test/simple/test-stream-big-push.js +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var stream = require('stream'); -var str = 'asdfasdfasdfasdfasdf'; - -var r = new stream.Readable({ - highWaterMark: 5, - encoding: 'utf8' -}); - -var reads = 0; -var eofed = false; -var ended = false; - -r._read = function(n) { - if (reads === 0) { - setTimeout(function() { - r.push(str); - }); - reads++; - } else if (reads === 1) { - var ret = r.push(str); - assert.equal(ret, false); - reads++; - } else { - assert(!eofed); - eofed = true; - r.push(null); - } -}; - -r.on('end', function() { - ended = true; -}); - -// push some data in to start. -// we've never gotten any read event at this point. -var ret = r.push(str); -// should be false. > hwm -assert(!ret); -var chunk = r.read(); -assert.equal(chunk, str); -chunk = r.read(); -assert.equal(chunk, null); - -r.once('readable', function() { - // this time, we'll get *all* the remaining data, because - // it's been added synchronously, as the read WOULD take - // us below the hwm, and so it triggered a _read() again, - // which synchronously added more, which we then return. - chunk = r.read(); - assert.equal(chunk, str + str); - - chunk = r.read(); - assert.equal(chunk, null); -}); - -process.on('exit', function() { - assert(eofed); - assert(ended); - assert.equal(reads, 2); - console.log('ok'); -}); diff --git a/test/simple/test-stream-duplex.js b/test/simple/test-stream-duplex.js deleted file mode 100644 index 61f314939..000000000 --- a/test/simple/test-stream-duplex.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Duplex = require('stream').Transform; - -var stream = new Duplex({ objectMode: true }); - -assert(stream._readableState.objectMode); -assert(stream._writableState.objectMode); - -var written; -var read; - -stream._write = function (obj, _, cb) { - written = obj; - cb(); -}; - -stream._read = function () {}; - -stream.on('data', function (obj) { - read = obj; -}); - -stream.push({ val: 1 }); -stream.end({ val: 2 }); - -process.on('exit', function () { - assert(read.val === 1); - assert(written.val === 2); -}); diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js deleted file mode 100644 index bb7377776..000000000 --- a/test/simple/test-stream-end-paused.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var gotEnd = false; - -// Make sure we don't miss the end event for paused 0-length streams - -var Readable = require('stream').Readable; -var stream = new Readable(); -var calledRead = false; -stream._read = function() { - assert(!calledRead); - calledRead = true; - this.push(null); -}; - -stream.on('data', function() { - throw new Error('should not ever get data'); -}); -stream.pause(); - -setTimeout(function() { - stream.on('end', function() { - gotEnd = true; - }); - stream.resume(); -}); - -process.on('exit', function() { - assert(gotEnd); - assert(calledRead); - console.log('ok'); -}); diff --git a/test/simple/test-stream-ispaused.js b/test/simple/test-stream-ispaused.js deleted file mode 100644 index 91f4f512f..000000000 --- a/test/simple/test-stream-ispaused.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. - -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: - -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. - -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); - -var stream = require('stream'); - -var readable = new stream.Readable; - -// _read is a noop, here. -readable._read = Function(); - -// default state of a stream is not "paused" -assert.ok(!readable.isPaused()); - -// make the stream start flowing... -readable.on('data', Function()); - -// still not paused. -assert.ok(!readable.isPaused()); - -readable.pause(); -assert.ok(readable.isPaused()); -readable.resume(); -assert.ok(!readable.isPaused()); diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js deleted file mode 100644 index b46ee90ad..000000000 --- a/test/simple/test-stream-pipe-after-end.js +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); -var util = require('util'); - -util.inherits(TestReadable, Readable); -function TestReadable(opt) { - if (!(this instanceof TestReadable)) - return new TestReadable(opt); - Readable.call(this, opt); - this._ended = false; -} - -TestReadable.prototype._read = function(n) { - if (this._ended) - this.emit('error', new Error('_read called twice')); - this._ended = true; - this.push(null); -}; - -util.inherits(TestWritable, Writable); -function TestWritable(opt) { - if (!(this instanceof TestWritable)) - return new TestWritable(opt); - Writable.call(this, opt); - this._written = []; -} - -TestWritable.prototype._write = function(chunk, encoding, cb) { - this._written.push(chunk); - cb(); -}; - -// this one should not emit 'end' until we read() from it later. -var ender = new TestReadable(); -var enderEnded = false; - -// what happens when you pipe() a Readable that's already ended? -var piper = new TestReadable(); -// pushes EOF null, and length=0, so this will trigger 'end' -piper.read(); - -setTimeout(function() { - ender.on('end', function() { - enderEnded = true; - }); - assert(!enderEnded); - var c = ender.read(); - assert.equal(c, null); - - var w = new TestWritable(); - var writableFinished = false; - w.on('finish', function() { - writableFinished = true; - }); - piper.pipe(w); - - process.on('exit', function() { - assert(enderEnded); - assert(writableFinished); - console.log('ok'); - }); -}); diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js deleted file mode 100644 index f68935852..000000000 --- a/test/simple/test-stream-pipe-cleanup.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// This test asserts that Stream.prototype.pipe does not leave listeners -// hanging on the source or dest. - -var common = require('../common'); -var stream = require('stream'); -var assert = require('assert'); -var util = require('util'); - -function Writable() { - this.writable = true; - this.endCalls = 0; - stream.Stream.call(this); -} -util.inherits(Writable, stream.Stream); -Writable.prototype.end = function() { - this.endCalls++; -}; - -Writable.prototype.destroy = function() { - this.endCalls++; -}; - -function Readable() { - this.readable = true; - stream.Stream.call(this); -} -util.inherits(Readable, stream.Stream); - -function Duplex() { - this.readable = true; - Writable.call(this); -} -util.inherits(Duplex, Writable); - -var i = 0; -var limit = 100; - -var w = new Writable(); - -var r; - -for (i = 0; i < limit; i++) { - r = new Readable(); - r.pipe(w); - r.emit('end'); -} -assert.equal(0, r.listeners('end').length); -assert.equal(limit, w.endCalls); - -w.endCalls = 0; - -for (i = 0; i < limit; i++) { - r = new Readable(); - r.pipe(w); - r.emit('close'); -} -assert.equal(0, r.listeners('close').length); -assert.equal(limit, w.endCalls); - -w.endCalls = 0; - -r = new Readable(); - -for (i = 0; i < limit; i++) { - w = new Writable(); - r.pipe(w); - w.emit('close'); -} -assert.equal(0, w.listeners('close').length); - -r = new Readable(); -w = new Writable(); -var d = new Duplex(); -r.pipe(d); // pipeline A -d.pipe(w); // pipeline B -assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup -assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup -assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup -assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup -assert.equal(w.listeners('end').length, 0); -assert.equal(w.listeners('close').length, 1); // B.cleanup - -r.emit('end'); -assert.equal(d.endCalls, 1); -assert.equal(w.endCalls, 0); -assert.equal(r.listeners('end').length, 0); -assert.equal(r.listeners('close').length, 0); -assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup -assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup -assert.equal(w.listeners('end').length, 0); -assert.equal(w.listeners('close').length, 1); // B.cleanup - -d.emit('end'); -assert.equal(d.endCalls, 1); -assert.equal(w.endCalls, 1); -assert.equal(r.listeners('end').length, 0); -assert.equal(r.listeners('close').length, 0); -assert.equal(d.listeners('end').length, 0); -assert.equal(d.listeners('close').length, 0); -assert.equal(w.listeners('end').length, 0); -assert.equal(w.listeners('close').length, 0); diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js deleted file mode 100644 index c5d724b78..000000000 --- a/test/simple/test-stream-pipe-error-handling.js +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var Stream = require('stream').Stream; - -(function testErrorListenerCatches() { - var source = new Stream(); - var dest = new Stream(); - - source.pipe(dest); - - var gotErr = null; - source.on('error', function(err) { - gotErr = err; - }); - - var err = new Error('This stream turned into bacon.'); - source.emit('error', err); - assert.strictEqual(gotErr, err); -})(); - -(function testErrorWithoutListenerThrows() { - var source = new Stream(); - var dest = new Stream(); - - source.pipe(dest); - - var err = new Error('This stream turned into bacon.'); - - var gotErr = null; - try { - source.emit('error', err); - } catch (e) { - gotErr = e; - } - - assert.strictEqual(gotErr, err); -})(); - -(function testErrorWithRemovedListenerThrows() { - var EE = require('events').EventEmitter; - var R = Stream.Readable; - var W = Stream.Writable; - - var r = new R; - var w = new W; - var removed = false; - var didTest = false; - - process.on('exit', function() { - assert(didTest); - console.log('ok'); - }); - - r._read = function() { - setTimeout(function() { - assert(removed); - assert.throws(function() { - w.emit('error', new Error('fail')); - }); - didTest = true; - }); - }; - - w.on('error', myOnError); - r.pipe(w); - w.removeListener('error', myOnError); - removed = true; - - function myOnError(er) { - throw new Error('this should not happen'); - } -})(); - -(function testErrorWithRemovedListenerThrows() { - var EE = require('events').EventEmitter; - var R = Stream.Readable; - var W = Stream.Writable; - - var r = new R; - var w = new W; - var removed = false; - var didTest = false; - var caught = false; - - process.on('exit', function() { - assert(didTest); - console.log('ok'); - }); - - r._read = function() { - setTimeout(function() { - assert(removed); - w.emit('error', new Error('fail')); - didTest = true; - }); - }; - - w.on('error', myOnError); - w._write = function() {}; - - r.pipe(w); - // Removing some OTHER random listener should not do anything - w.removeListener('error', function() {}); - removed = true; - - function myOnError(er) { - assert(!caught); - caught = true; - } -})(); diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js deleted file mode 100644 index cb9d5fe8c..000000000 --- a/test/simple/test-stream-pipe-event.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var stream = require('stream'); -var assert = require('assert'); -var util = require('util'); - -function Writable() { - this.writable = true; - stream.Stream.call(this); -} -util.inherits(Writable, stream.Stream); - -function Readable() { - this.readable = true; - stream.Stream.call(this); -} -util.inherits(Readable, stream.Stream); - -var passed = false; - -var w = new Writable(); -w.on('pipe', function(src) { - passed = true; -}); - -var r = new Readable(); -r.pipe(w); - -assert.ok(passed); diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js deleted file mode 100644 index f2e6ec29c..000000000 --- a/test/simple/test-stream-push-order.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var Readable = require('stream').Readable; -var assert = require('assert'); - -var s = new Readable({ - highWaterMark: 20, - encoding: 'ascii' -}); - -var list = ['1', '2', '3', '4', '5', '6']; - -s._read = function (n) { - var one = list.shift(); - if (!one) { - s.push(null); - } else { - var two = list.shift(); - s.push(one); - s.push(two); - } -}; - -var v = s.read(0); - -// ACTUALLY [1, 3, 5, 6, 4, 2] - -process.on("exit", function () { - assert.deepEqual(s._readableState.buffer, - ['1', '2', '3', '4', '5', '6']); - console.log("ok"); -}); diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js deleted file mode 100644 index 06f43dc1c..000000000 --- a/test/simple/test-stream-push-strings.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Readable = require('stream').Readable; -var util = require('util'); - -util.inherits(MyStream, Readable); -function MyStream(options) { - Readable.call(this, options); - this._chunks = 3; -} - -MyStream.prototype._read = function(n) { - switch (this._chunks--) { - case 0: - return this.push(null); - case 1: - return setTimeout(function() { - this.push('last chunk'); - }.bind(this), 100); - case 2: - return this.push('second to last chunk'); - case 3: - return process.nextTick(function() { - this.push('first chunk'); - }.bind(this)); - default: - throw new Error('?'); - } -}; - -var ms = new MyStream(); -var results = []; -ms.on('readable', function() { - var chunk; - while (null !== (chunk = ms.read())) - results.push(chunk + ''); -}); - -var expect = [ 'first chunksecond to last chunk', 'last chunk' ]; -process.on('exit', function() { - assert.equal(ms._chunks, -1); - assert.deepEqual(results, expect); - console.log('ok'); -}); diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js deleted file mode 100644 index ba6a57724..000000000 --- a/test/simple/test-stream-readable-event.js +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Readable = require('stream').Readable; - -(function first() { - // First test, not reading when the readable is added. - // make sure that on('readable', ...) triggers a readable event. - var r = new Readable({ - highWaterMark: 3 - }); - - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; - - // This triggers a 'readable' event, which is lost. - r.push(new Buffer('blerg')); - - var caughtReadable = false; - setTimeout(function() { - // we're testing what we think we are - assert(!r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(!_readCalled); - - assert(caughtReadable); - console.log('ok 1'); - }); -})(); - -(function second() { - // second test, make sure that readable is re-emitted if there's - // already a length, while it IS reading. - - var r = new Readable({ - highWaterMark: 3 - }); - - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; - - // This triggers a 'readable' event, which is lost. - r.push(new Buffer('bl')); - - var caughtReadable = false; - setTimeout(function() { - // assert we're testing what we think we are - assert(r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(_readCalled); - - assert(caughtReadable); - console.log('ok 2'); - }); -})(); - -(function third() { - // Third test, not reading when the stream has not passed - // the highWaterMark but *has* reached EOF. - var r = new Readable({ - highWaterMark: 30 - }); - - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; - - // This triggers a 'readable' event, which is lost. - r.push(new Buffer('blerg')); - r.push(null); - - var caughtReadable = false; - setTimeout(function() { - // assert we're testing what we think we are - assert(!r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(!_readCalled); - - assert(caughtReadable); - console.log('ok 3'); - }); -})(); diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js deleted file mode 100644 index 2891ad6db..000000000 --- a/test/simple/test-stream-readable-flow-recursion.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// this test verifies that passing a huge number to read(size) -// will push up the highWaterMark, and cause the stream to read -// more data continuously, but without triggering a nextTick -// warning or RangeError. - -var Readable = require('stream').Readable; - -// throw an error if we trigger a nextTick warning. -process.throwDeprecation = true; - -var stream = new Readable({ highWaterMark: 2 }); -var reads = 0; -var total = 5000; -stream._read = function(size) { - reads++; - size = Math.min(size, total); - total -= size; - if (size === 0) - stream.push(null); - else - stream.push(new Buffer(size)); -}; - -var depth = 0; - -function flow(stream, size, callback) { - depth += 1; - var chunk = stream.read(size); - - if (!chunk) - stream.once('readable', flow.bind(null, stream, size, callback)); - else - callback(chunk); - - depth -= 1; - console.log('flow(' + depth + '): exit'); -} - -flow(stream, 5000, function() { - console.log('complete (' + depth + ')'); -}); - -process.on('exit', function(code) { - assert.equal(reads, 2); - // we pushed up the high water mark - assert.equal(stream._readableState.highWaterMark, 8192); - // length is 0 right now, because we pulled it all out. - assert.equal(stream._readableState.length, 0); - assert(!code); - assert.equal(depth, 0); - console.log('ok'); -}); diff --git a/test/simple/test-stream-transform-objectmode-falsey-value.js b/test/simple/test-stream-transform-objectmode-falsey-value.js deleted file mode 100644 index 31b5bbaaf..000000000 --- a/test/simple/test-stream-transform-objectmode-falsey-value.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var stream = require('stream'); -var PassThrough = stream.PassThrough; - -var src = new PassThrough({ objectMode: true }); -var tx = new PassThrough({ objectMode: true }); -var dest = new PassThrough({ objectMode: true }); - -var expect = [ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; -var results = []; -process.on('exit', function() { - assert.deepEqual(results, expect); - console.log('ok'); -}); - -dest.on('data', function(x) { - results.push(x); -}); - -src.pipe(tx).pipe(dest); - -var i = -1; -var int = setInterval(function() { - if (i > 10) { - src.end(); - clearInterval(int); - } else { - src.write(i++); - } -}); diff --git a/test/simple/test-stream-transform-split-objectmode.js b/test/simple/test-stream-transform-split-objectmode.js deleted file mode 100644 index 72a2f0ace..000000000 --- a/test/simple/test-stream-transform-split-objectmode.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Transform = require('stream').Transform; - -var parser = new Transform({ readableObjectMode : true }); - -assert(parser._readableState.objectMode); -assert(!parser._writableState.objectMode); -assert(parser._readableState.highWaterMark === 16); -assert(parser._writableState.highWaterMark === (16 * 1024)); - -parser._transform = function (chunk, enc, callback) { - callback(null, { val : chunk[0] }); -}; - -var parsed; - -parser.on('data', function (obj) { - parsed = obj; -}); - -parser.end(new Buffer([42])); - -process.on('exit', function () { - assert(parsed.val === 42); -}); - - -var serializer = new Transform({ writableObjectMode : true }); - -assert(!serializer._readableState.objectMode); -assert(serializer._writableState.objectMode); -assert(serializer._readableState.highWaterMark === (16 * 1024)); -assert(serializer._writableState.highWaterMark === 16); - -serializer._transform = function (obj, _, callback) { - callback(null, new Buffer([obj.val])); -}; - -var serialized; - -serializer.on('data', function (chunk) { - serialized = chunk; -}); - -serializer.write({ val : 42 }); - -process.on('exit', function () { - assert(serialized[0] === 42); -}); diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js deleted file mode 100644 index 0c9647650..000000000 --- a/test/simple/test-stream-unshift-empty-chunk.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// This test verifies that stream.unshift(Buffer(0)) or -// stream.unshift('') does not set state.reading=false. -var Readable = require('stream').Readable; - -var r = new Readable(); -var nChunks = 10; -var chunk = new Buffer(10); -chunk.fill('x'); - -r._read = function(n) { - setTimeout(function() { - r.push(--nChunks === 0 ? null : chunk); - }); -}; - -var readAll = false; -var seen = []; -r.on('readable', function() { - var chunk; - while (chunk = r.read()) { - seen.push(chunk.toString()); - // simulate only reading a certain amount of the data, - // and then putting the rest of the chunk back into the - // stream, like a parser might do. We just fill it with - // 'y' so that it's easy to see which bits were touched, - // and which were not. - var putBack = new Buffer(readAll ? 0 : 5); - putBack.fill('y'); - readAll = !readAll; - r.unshift(putBack); - } -}); - -var expect = - [ 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy', - 'xxxxxxxxxx', - 'yyyyy' ]; - -r.on('end', function() { - assert.deepEqual(seen, expect); - console.log('ok'); -}); diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js deleted file mode 100644 index 83fd9fa20..000000000 --- a/test/simple/test-stream-unshift-read-race.js +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// This test verifies that: -// 1. unshift() does not cause colliding _read() calls. -// 2. unshift() after the 'end' event is an error, but after the EOF -// signalling null, it is ok, and just creates a new readable chunk. -// 3. push() after the EOF signaling null is an error. -// 4. _read() is not called after pushing the EOF null chunk. - -var stream = require('stream'); -var hwm = 10; -var r = stream.Readable({ highWaterMark: hwm }); -var chunks = 10; -var t = (chunks * 5); - -var data = new Buffer(chunks * hwm + Math.ceil(hwm / 2)); -for (var i = 0; i < data.length; i++) { - var c = 'asdf'.charCodeAt(i % 4); - data[i] = c; -} - -var pos = 0; -var pushedNull = false; -r._read = function(n) { - assert(!pushedNull, '_read after null push'); - - // every third chunk is fast - push(!(chunks % 3)); - - function push(fast) { - assert(!pushedNull, 'push() after null push'); - var c = pos >= data.length ? null : data.slice(pos, pos + n); - pushedNull = c === null; - if (fast) { - pos += n; - r.push(c); - if (c === null) pushError(); - } else { - setTimeout(function() { - pos += n; - r.push(c); - if (c === null) pushError(); - }); - } - } -}; - -function pushError() { - assert.throws(function() { - r.push(new Buffer(1)); - }); -} - - -var w = stream.Writable(); -var written = []; -w._write = function(chunk, encoding, cb) { - written.push(chunk.toString()); - cb(); -}; - -var ended = false; -r.on('end', function() { - assert(!ended, 'end emitted more than once'); - assert.throws(function() { - r.unshift(new Buffer(1)); - }); - ended = true; - w.end(); -}); - -r.on('readable', function() { - var chunk; - while (null !== (chunk = r.read(10))) { - w.write(chunk); - if (chunk.length > 4) - r.unshift(new Buffer('1234')); - } -}); - -var finished = false; -w.on('finish', function() { - finished = true; - // each chunk should start with 1234, and then be asfdasdfasdf... - // The first got pulled out before the first unshift('1234'), so it's - // lacking that piece. - assert.equal(written[0], 'asdfasdfas'); - var asdf = 'd'; - console.error('0: %s', written[0]); - for (var i = 1; i < written.length; i++) { - console.error('%s: %s', i.toString(32), written[i]); - assert.equal(written[i].slice(0, 4), '1234'); - for (var j = 4; j < written[i].length; j++) { - var c = written[i].charAt(j); - assert.equal(c, asdf); - switch (asdf) { - case 'a': asdf = 's'; break; - case 's': asdf = 'd'; break; - case 'd': asdf = 'f'; break; - case 'f': asdf = 'a'; break; - } - } - } -}); - -process.on('exit', function() { - assert.equal(written.length, 18); - assert(ended, 'stream ended'); - assert(finished, 'stream finished'); - console.log('ok'); -}); diff --git a/test/simple/test-stream-writable-change-default-encoding.js b/test/simple/test-stream-writable-change-default-encoding.js deleted file mode 100644 index eb71cf2b4..000000000 --- a/test/simple/test-stream-writable-change-default-encoding.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var stream = require('stream'); -var util = require('util'); - -function MyWritable(fn, options) { - stream.Writable.call(this, options); - this.fn = fn; -}; - -util.inherits(MyWritable, stream.Writable); - -MyWritable.prototype._write = function (chunk, encoding, callback) { - this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); - callback(); -}; - -(function defaultCondingIsUtf8() { - var m = new MyWritable(function(isBuffer, type, enc) { - assert.equal(enc, 'utf8'); - }, { decodeStrings: false }); - m.write('foo'); - m.end(); -}()); - -(function changeDefaultEncodingToAscii() { - var m = new MyWritable(function(isBuffer, type, enc) { - assert.equal(enc, 'ascii'); - }, { decodeStrings: false }); - m.setDefaultEncoding('ascii'); - m.write('bar'); - m.end(); -}()); - -assert.throws(function changeDefaultEncodingToInvalidValue() { - var m = new MyWritable(function(isBuffer, type, enc) { - }, { decodeStrings: false }); - m.setDefaultEncoding({}); - m.write('bar'); - m.end(); -}, TypeError); - -(function checkVairableCaseEncoding() { - var m = new MyWritable(function(isBuffer, type, enc) { - assert.equal(enc, 'ascii'); - }, { decodeStrings: false }); - m.setDefaultEncoding('AsCii'); - m.write('bar'); - m.end(); -}()); diff --git a/test/simple/test-stream-writable-decoded-encoding.js b/test/simple/test-stream-writable-decoded-encoding.js deleted file mode 100644 index 8e2624b25..000000000 --- a/test/simple/test-stream-writable-decoded-encoding.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var stream = require('stream'); -var util = require('util'); - -function MyWritable(fn, options) { - stream.Writable.call(this, options); - this.fn = fn; -}; - -util.inherits(MyWritable, stream.Writable); - -MyWritable.prototype._write = function (chunk, encoding, callback) { - this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); - callback(); -}; - -;(function decodeStringsTrue() { - var m = new MyWritable(function(isBuffer, type, enc) { - assert(isBuffer); - assert.equal(type, 'object'); - assert.equal(enc, 'buffer'); - console.log('ok - decoded string is decoded'); - }, { decodeStrings: true }); - m.write('some-text', 'utf8'); - m.end(); -})(); - -;(function decodeStringsFalse() { - var m = new MyWritable(function(isBuffer, type, enc) { - assert(!isBuffer); - assert.equal(type, 'string'); - assert.equal(enc, 'utf8'); - console.log('ok - un-decoded string is not decoded'); - }, { decodeStrings: false }); - m.write('some-text', 'utf8'); - m.end(); -})(); diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js deleted file mode 100644 index 5b49e6e41..000000000 --- a/test/simple/test-stream-writev.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var stream = require('stream'); - -var queue = []; -for (var decode = 0; decode < 2; decode++) { - for (var uncork = 0; uncork < 2; uncork++) { - for (var multi = 0; multi < 2; multi++) { - queue.push([!!decode, !!uncork, !!multi]); - } - } -} - -run(); - -function run() { - var t = queue.pop(); - if (t) - test(t[0], t[1], t[2], run); - else - console.log('ok'); -} - -function test(decode, uncork, multi, next) { - console.log('# decode=%j uncork=%j multi=%j', decode, uncork, multi); - var counter = 0; - var expectCount = 0; - function cnt(msg) { - expectCount++; - var expect = expectCount; - var called = false; - return function(er) { - if (er) - throw er; - called = true; - counter++; - assert.equal(counter, expect); - }; - } - - var w = new stream.Writable({ decodeStrings: decode }); - w._write = function(chunk, e, cb) { - assert(false, 'Should not call _write'); - }; - - var expectChunks = decode ? - [{ encoding: 'buffer', - chunk: [104, 101, 108, 108, 111, 44, 32] }, - { encoding: 'buffer', chunk: [119, 111, 114, 108, 100] }, - { encoding: 'buffer', chunk: [33] }, - { encoding: 'buffer', - chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, - { encoding: 'buffer', - chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173] }] : - [{ encoding: 'ascii', chunk: 'hello, ' }, - { encoding: 'utf8', chunk: 'world' }, - { encoding: 'buffer', chunk: [33] }, - { encoding: 'binary', chunk: '\nand then...' }, - { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' }]; - - var actualChunks; - w._writev = function(chunks, cb) { - actualChunks = chunks.map(function(chunk) { - return { - encoding: chunk.encoding, - chunk: Buffer.isBuffer(chunk.chunk) ? - Array.prototype.slice.call(chunk.chunk) : chunk.chunk - }; - }); - cb(); - }; - - w.cork(); - w.write('hello, ', 'ascii', cnt('hello')); - w.write('world', 'utf8', cnt('world')); - - if (multi) - w.cork(); - - w.write(new Buffer('!'), 'buffer', cnt('!')); - w.write('\nand then...', 'binary', cnt('and then')); - - if (multi) - w.uncork(); - - w.write('facebea7deadbeefdecafbad', 'hex', cnt('hex')); - - if (uncork) - w.uncork(); - - w.end(cnt('end')); - - w.on('finish', function() { - // make sure finish comes after all the write cb - cnt('finish')(); - assert.deepEqual(expectChunks, actualChunks); - next(); - }); -} diff --git a/test/simple/test-stream2-base64-single-char-read-end.js b/test/simple/test-stream2-base64-single-char-read-end.js deleted file mode 100644 index 5a3834128..000000000 --- a/test/simple/test-stream2-base64-single-char-read-end.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var R = require('_stream_readable'); -var W = require('_stream_writable'); -var assert = require('assert'); - -var src = new R({encoding: 'base64'}); -var dst = new W(); -var hasRead = false; -var accum = []; -var timeout; - -src._read = function(n) { - if(!hasRead) { - hasRead = true; - process.nextTick(function() { - src.push(new Buffer('1')); - src.push(null); - }); - }; -}; - -dst._write = function(chunk, enc, cb) { - accum.push(chunk); - cb(); -}; - -src.on('end', function() { - assert.equal(Buffer.concat(accum) + '', 'MQ=='); - clearTimeout(timeout); -}) - -src.pipe(dst); - -timeout = setTimeout(function() { - assert.fail('timed out waiting for _write'); -}, 100); diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js deleted file mode 100644 index 6cdd4e994..000000000 --- a/test/simple/test-stream2-compatibility.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var R = require('_stream_readable'); -var assert = require('assert'); - -var util = require('util'); -var EE = require('events').EventEmitter; - -var ondataCalled = 0; - -function TestReader() { - R.apply(this); - this._buffer = new Buffer(100); - this._buffer.fill('x'); - - this.on('data', function() { - ondataCalled++; - }); -} - -util.inherits(TestReader, R); - -TestReader.prototype._read = function(n) { - this.push(this._buffer); - this._buffer = new Buffer(0); -}; - -var reader = new TestReader(); -setImmediate(function() { - assert.equal(ondataCalled, 1); - console.log('ok'); -}); diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js deleted file mode 100644 index 39b274f97..000000000 --- a/test/simple/test-stream2-finish-pipe.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var stream = require('stream'); -var Buffer = require('buffer').Buffer; - -var r = new stream.Readable(); -r._read = function(size) { - r.push(new Buffer(size)); -}; - -var w = new stream.Writable(); -w._write = function(data, encoding, cb) { - cb(null); -}; - -r.pipe(w); - -// This might sound unrealistic, but it happens in net.js. When -// `socket.allowHalfOpen === false`, EOF will cause `.destroySoon()` call which -// ends the writable side of net.Socket. -w.end(); diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js deleted file mode 100644 index e16240628..000000000 --- a/test/simple/test-stream2-fs.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var R = require('_stream_readable'); -var assert = require('assert'); - -var fs = require('fs'); -var FSReadable = fs.ReadStream; - -var path = require('path'); -var file = path.resolve(common.fixturesDir, 'x1024.txt'); - -var size = fs.statSync(file).size; - -var expectLengths = [1024]; - -var util = require('util'); -var Stream = require('stream'); - -util.inherits(TestWriter, Stream); - -function TestWriter() { - Stream.apply(this); - this.buffer = []; - this.length = 0; -} - -TestWriter.prototype.write = function(c) { - this.buffer.push(c.toString()); - this.length += c.length; - return true; -}; - -TestWriter.prototype.end = function(c) { - if (c) this.buffer.push(c.toString()); - this.emit('results', this.buffer); -} - -var r = new FSReadable(file); -var w = new TestWriter(); - -w.on('results', function(res) { - console.error(res, w.length); - assert.equal(w.length, size); - var l = 0; - assert.deepEqual(res.map(function (c) { - return c.length; - }), expectLengths); - console.log('ok'); -}); - -r.pipe(w); diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js deleted file mode 100644 index 15cffc2ac..000000000 --- a/test/simple/test-stream2-httpclient-response-end.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var http = require('http'); -var msg = 'Hello'; -var readable_event = false; -var end_event = false; -var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end(msg); -}).listen(common.PORT, function() { - http.get({port: common.PORT}, function(res) { - var data = ''; - res.on('readable', function() { - console.log('readable event'); - readable_event = true; - data += res.read(); - }); - res.on('end', function() { - console.log('end event'); - end_event = true; - assert.strictEqual(msg, data); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert(readable_event); - assert(end_event); -}); - diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js deleted file mode 100644 index 2fbfbcab3..000000000 --- a/test/simple/test-stream2-large-read-stall.js +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); - -// If everything aligns so that you do a read(n) of exactly the -// remaining buffer, then make sure that 'end' still emits. - -var READSIZE = 100; -var PUSHSIZE = 20; -var PUSHCOUNT = 1000; -var HWM = 50; - -var Readable = require('stream').Readable; -var r = new Readable({ - highWaterMark: HWM -}); -var rs = r._readableState; - -r._read = push; - -r.on('readable', function() { - console.error('>> readable'); - do { - console.error(' > read(%d)', READSIZE); - var ret = r.read(READSIZE); - console.error(' < %j (%d remain)', ret && ret.length, rs.length); - } while (ret && ret.length === READSIZE); - - console.error('<< after read()', - ret && ret.length, - rs.needReadable, - rs.length); -}); - -var endEmitted = false; -r.on('end', function() { - endEmitted = true; - console.error('end'); -}); - -var pushes = 0; -function push() { - if (pushes > PUSHCOUNT) - return; - - if (pushes++ === PUSHCOUNT) { - console.error(' push(EOF)'); - return r.push(null); - } - - console.error(' push #%d', pushes); - if (r.push(new Buffer(PUSHSIZE))) - setTimeout(push); -} - -// start the flow -var ret = r.read(0); - -process.on('exit', function() { - assert.equal(pushes, PUSHCOUNT + 1); - assert(endEmitted); -}); diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js deleted file mode 100644 index 3e6931dce..000000000 --- a/test/simple/test-stream2-objects.js +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); -var assert = require('assert'); - -// tiny node-tap lookalike. -var tests = []; -var count = 0; - -function test(name, fn) { - count++; - tests.push([name, fn]); -} - -function run() { - var next = tests.shift(); - if (!next) - return console.error('ok'); - - var name = next[0]; - var fn = next[1]; - console.log('# %s', name); - fn({ - same: assert.deepEqual, - equal: assert.equal, - end: function() { - count--; - run(); - } - }); -} - -// ensure all tests have run -process.on('exit', function() { - assert.equal(count, 0); -}); - -process.nextTick(run); - -function toArray(callback) { - var stream = new Writable({ objectMode: true }); - var list = []; - stream.write = function(chunk) { - list.push(chunk); - }; - - stream.end = function() { - callback(list); - }; - - return stream; -} - -function fromArray(list) { - var r = new Readable({ objectMode: true }); - r._read = noop; - list.forEach(function(chunk) { - r.push(chunk); - }); - r.push(null); - - return r; -} - -function noop() {} - -test('can read objects from stream', function(t) { - var r = fromArray([{ one: '1'}, { two: '2' }]); - - var v1 = r.read(); - var v2 = r.read(); - var v3 = r.read(); - - assert.deepEqual(v1, { one: '1' }); - assert.deepEqual(v2, { two: '2' }); - assert.deepEqual(v3, null); - - t.end(); -}); - -test('can pipe objects into stream', function(t) { - var r = fromArray([{ one: '1'}, { two: '2' }]); - - r.pipe(toArray(function(list) { - assert.deepEqual(list, [ - { one: '1' }, - { two: '2' } - ]); - - t.end(); - })); -}); - -test('read(n) is ignored', function(t) { - var r = fromArray([{ one: '1'}, { two: '2' }]); - - var value = r.read(2); - - assert.deepEqual(value, { one: '1' }); - - t.end(); -}); - -test('can read objects from _read (sync)', function(t) { - var r = new Readable({ objectMode: true }); - var list = [{ one: '1'}, { two: '2' }]; - r._read = function(n) { - var item = list.shift(); - r.push(item || null); - }; - - r.pipe(toArray(function(list) { - assert.deepEqual(list, [ - { one: '1' }, - { two: '2' } - ]); - - t.end(); - })); -}); - -test('can read objects from _read (async)', function(t) { - var r = new Readable({ objectMode: true }); - var list = [{ one: '1'}, { two: '2' }]; - r._read = function(n) { - var item = list.shift(); - process.nextTick(function() { - r.push(item || null); - }); - }; - - r.pipe(toArray(function(list) { - assert.deepEqual(list, [ - { one: '1' }, - { two: '2' } - ]); - - t.end(); - })); -}); - -test('can read strings as objects', function(t) { - var r = new Readable({ - objectMode: true - }); - r._read = noop; - var list = ['one', 'two', 'three']; - list.forEach(function(str) { - r.push(str); - }); - r.push(null); - - r.pipe(toArray(function(array) { - assert.deepEqual(array, list); - - t.end(); - })); -}); - -test('read(0) for object streams', function(t) { - var r = new Readable({ - objectMode: true - }); - r._read = noop; - - r.push('foobar'); - r.push(null); - - var v = r.read(0); - - r.pipe(toArray(function(array) { - assert.deepEqual(array, ['foobar']); - - t.end(); - })); -}); - -test('falsey values', function(t) { - var r = new Readable({ - objectMode: true - }); - r._read = noop; - - r.push(false); - r.push(0); - r.push(''); - r.push(null); - - r.pipe(toArray(function(array) { - assert.deepEqual(array, [false, 0, '']); - - t.end(); - })); -}); - -test('high watermark _read', function(t) { - var r = new Readable({ - highWaterMark: 6, - objectMode: true - }); - var calls = 0; - var list = ['1', '2', '3', '4', '5', '6', '7', '8']; - - r._read = function(n) { - calls++; - }; - - list.forEach(function(c) { - r.push(c); - }); - - var v = r.read(); - - assert.equal(calls, 0); - assert.equal(v, '1'); - - var v2 = r.read(); - assert.equal(v2, '2'); - - var v3 = r.read(); - assert.equal(v3, '3'); - - assert.equal(calls, 1); - - t.end(); -}); - -test('high watermark push', function(t) { - var r = new Readable({ - highWaterMark: 6, - objectMode: true - }); - r._read = function(n) {}; - for (var i = 0; i < 6; i++) { - var bool = r.push(i); - assert.equal(bool, i === 5 ? false : true); - } - - t.end(); -}); - -test('can write objects to stream', function(t) { - var w = new Writable({ objectMode: true }); - - w._write = function(chunk, encoding, cb) { - assert.deepEqual(chunk, { foo: 'bar' }); - cb(); - }; - - w.on('finish', function() { - t.end(); - }); - - w.write({ foo: 'bar' }); - w.end(); -}); - -test('can write multiple objects to stream', function(t) { - var w = new Writable({ objectMode: true }); - var list = []; - - w._write = function(chunk, encoding, cb) { - list.push(chunk); - cb(); - }; - - w.on('finish', function() { - assert.deepEqual(list, [0, 1, 2, 3, 4]); - - t.end(); - }); - - w.write(0); - w.write(1); - w.write(2); - w.write(3); - w.write(4); - w.end(); -}); - -test('can write strings as objects', function(t) { - var w = new Writable({ - objectMode: true - }); - var list = []; - - w._write = function(chunk, encoding, cb) { - list.push(chunk); - process.nextTick(cb); - }; - - w.on('finish', function() { - assert.deepEqual(list, ['0', '1', '2', '3', '4']); - - t.end(); - }); - - w.write('0'); - w.write('1'); - w.write('2'); - w.write('3'); - w.write('4'); - w.end(); -}); - -test('buffers finish until cb is called', function(t) { - var w = new Writable({ - objectMode: true - }); - var called = false; - - w._write = function(chunk, encoding, cb) { - assert.equal(chunk, 'foo'); - - process.nextTick(function() { - called = true; - cb(); - }); - }; - - w.on('finish', function() { - assert.equal(called, true); - - t.end(); - }); - - w.write('foo'); - w.end(); -}); diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js deleted file mode 100644 index cf7531cbd..000000000 --- a/test/simple/test-stream2-pipe-error-handling.js +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var stream = require('stream'); - -(function testErrorListenerCatches() { - var count = 1000; - - var source = new stream.Readable(); - source._read = function(n) { - n = Math.min(count, n); - count -= n; - source.push(new Buffer(n)); - }; - - var unpipedDest; - source.unpipe = function(dest) { - unpipedDest = dest; - stream.Readable.prototype.unpipe.call(this, dest); - }; - - var dest = new stream.Writable(); - dest._write = function(chunk, encoding, cb) { - cb(); - }; - - source.pipe(dest); - - var gotErr = null; - dest.on('error', function(err) { - gotErr = err; - }); - - var unpipedSource; - dest.on('unpipe', function(src) { - unpipedSource = src; - }); - - var err = new Error('This stream turned into bacon.'); - dest.emit('error', err); - assert.strictEqual(gotErr, err); - assert.strictEqual(unpipedSource, source); - assert.strictEqual(unpipedDest, dest); -})(); - -(function testErrorWithoutListenerThrows() { - var count = 1000; - - var source = new stream.Readable(); - source._read = function(n) { - n = Math.min(count, n); - count -= n; - source.push(new Buffer(n)); - }; - - var unpipedDest; - source.unpipe = function(dest) { - unpipedDest = dest; - stream.Readable.prototype.unpipe.call(this, dest); - }; - - var dest = new stream.Writable(); - dest._write = function(chunk, encoding, cb) { - cb(); - }; - - source.pipe(dest); - - var unpipedSource; - dest.on('unpipe', function(src) { - unpipedSource = src; - }); - - var err = new Error('This stream turned into bacon.'); - - var gotErr = null; - try { - dest.emit('error', err); - } catch (e) { - gotErr = e; - } - assert.strictEqual(gotErr, err); - assert.strictEqual(unpipedSource, source); - assert.strictEqual(unpipedDest, dest); -})(); diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js deleted file mode 100755 index 5e8e3cb28..000000000 --- a/test/simple/test-stream2-pipe-error-once-listener.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var assert = require('assert'); - -var util = require('util'); -var stream = require('stream'); - - -var Read = function() { - stream.Readable.call(this); -}; -util.inherits(Read, stream.Readable); - -Read.prototype._read = function(size) { - this.push('x'); - this.push(null); -}; - - -var Write = function() { - stream.Writable.call(this); -}; -util.inherits(Write, stream.Writable); - -Write.prototype._write = function(buffer, encoding, cb) { - this.emit('error', new Error('boom')); - this.emit('alldone'); -}; - -var read = new Read(); -var write = new Write(); - -write.once('error', function(err) {}); -write.once('alldone', function(err) { - console.log('ok'); -}); - -process.on('exit', function(c) { - console.error('error thrown even with listener'); -}); - -read.pipe(write); - diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js deleted file mode 100644 index b63edc308..000000000 --- a/test/simple/test-stream2-push.js +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var stream = require('stream'); -var Readable = stream.Readable; -var Writable = stream.Writable; -var assert = require('assert'); - -var util = require('util'); -var EE = require('events').EventEmitter; - - -// a mock thing a bit like the net.Socket/tcp_wrap.handle interaction - -var stream = new Readable({ - highWaterMark: 16, - encoding: 'utf8' -}); - -var source = new EE; - -stream._read = function() { - console.error('stream._read'); - readStart(); -}; - -var ended = false; -stream.on('end', function() { - ended = true; -}); - -source.on('data', function(chunk) { - var ret = stream.push(chunk); - console.error('data', stream._readableState.length); - if (!ret) - readStop(); -}); - -source.on('end', function() { - stream.push(null); -}); - -var reading = false; - -function readStart() { - console.error('readStart'); - reading = true; -} - -function readStop() { - console.error('readStop'); - reading = false; - process.nextTick(function() { - var r = stream.read(); - if (r !== null) - writer.write(r); - }); -} - -var writer = new Writable({ - decodeStrings: false -}); - -var written = []; - -var expectWritten = - [ 'asdfgasdfgasdfgasdfg', - 'asdfgasdfgasdfgasdfg', - 'asdfgasdfgasdfgasdfg', - 'asdfgasdfgasdfgasdfg', - 'asdfgasdfgasdfgasdfg', - 'asdfgasdfgasdfgasdfg' ]; - -writer._write = function(chunk, encoding, cb) { - console.error('WRITE %s', chunk); - written.push(chunk); - process.nextTick(cb); -}; - -writer.on('finish', finish); - - -// now emit some chunks. - -var chunk = "asdfg"; - -var set = 0; -readStart(); -data(); -function data() { - assert(reading); - source.emit('data', chunk); - assert(reading); - source.emit('data', chunk); - assert(reading); - source.emit('data', chunk); - assert(reading); - source.emit('data', chunk); - assert(!reading); - if (set++ < 5) - setTimeout(data, 10); - else - end(); -} - -function finish() { - console.error('finish'); - assert.deepEqual(written, expectWritten); - console.log('ok'); -} - -function end() { - source.emit('end'); - assert(!reading); - writer.end(stream.read()); - setTimeout(function() { - assert(ended); - }); -} diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js deleted file mode 100644 index e8a73053c..000000000 --- a/test/simple/test-stream2-read-sync-stack.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var Readable = require('stream').Readable; -var r = new Readable(); -var N = 256 * 1024; - -// Go ahead and allow the pathological case for this test. -// Yes, it's an infinite loop, that's the point. -process.maxTickDepth = N + 2; - -var reads = 0; -r._read = function(n) { - var chunk = reads++ === N ? null : new Buffer(1); - r.push(chunk); -}; - -r.on('readable', function onReadable() { - if (!(r._readableState.length % 256)) - console.error('readable', r._readableState.length); - r.read(N * 2); -}); - -var ended = false; -r.on('end', function onEnd() { - ended = true; -}); - -r.read(0); - -process.on('exit', function() { - assert(ended); - console.log('ok'); -}); diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js deleted file mode 100644 index d52af5edb..000000000 --- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Readable = require('stream').Readable; - -test1(); -test2(); - -function test1() { - var r = new Readable(); - - // should not end when we get a Buffer(0) or '' as the _read result - // that just means that there is *temporarily* no data, but to go - // ahead and try again later. - // - // note that this is very unusual. it only works for crypto streams - // because the other side of the stream will call read(0) to cycle - // data through openssl. that's why we set the timeouts to call - // r.read(0) again later, otherwise there is no more work being done - // and the process just exits. - - var buf = new Buffer(5); - buf.fill('x'); - var reads = 5; - r._read = function(n) { - switch (reads--) { - case 0: - return r.push(null); // EOF - case 1: - return r.push(buf); - case 2: - setTimeout(r.read.bind(r, 0), 50); - return r.push(new Buffer(0)); // Not-EOF! - case 3: - setTimeout(r.read.bind(r, 0), 50); - return process.nextTick(function() { - return r.push(new Buffer(0)); - }); - case 4: - setTimeout(r.read.bind(r, 0), 50); - return setTimeout(function() { - return r.push(new Buffer(0)); - }); - case 5: - return setTimeout(function() { - return r.push(buf); - }); - default: - throw new Error('unreachable'); - } - }; - - var results = []; - function flow() { - var chunk; - while (null !== (chunk = r.read())) - results.push(chunk + ''); - } - r.on('readable', flow); - r.on('end', function() { - results.push('EOF'); - }); - flow(); - - process.on('exit', function() { - assert.deepEqual(results, [ 'xxxxx', 'xxxxx', 'EOF' ]); - console.log('ok'); - }); -} - -function test2() { - var r = new Readable({ encoding: 'base64' }); - var reads = 5; - r._read = function(n) { - if (!reads--) - return r.push(null); // EOF - else - return r.push(new Buffer('x')); - }; - - var results = []; - function flow() { - var chunk; - while (null !== (chunk = r.read())) - results.push(chunk + ''); - } - r.on('readable', flow); - r.on('end', function() { - results.push('EOF'); - }); - flow(); - - process.on('exit', function() { - assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); - console.log('ok'); - }); -} diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js deleted file mode 100644 index 7c96ffe00..000000000 --- a/test/simple/test-stream2-readable-from-list.js +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common.js'); -var fromList = require('_stream_readable')._fromList; - -// tiny node-tap lookalike. -var tests = []; -var count = 0; - -function test(name, fn) { - count++; - tests.push([name, fn]); -} - -function run() { - var next = tests.shift(); - if (!next) - return console.error('ok'); - - var name = next[0]; - var fn = next[1]; - console.log('# %s', name); - fn({ - same: assert.deepEqual, - equal: assert.equal, - end: function () { - count--; - run(); - } - }); -} - -// ensure all tests have run -process.on("exit", function () { - assert.equal(count, 0); -}); - -process.nextTick(run); - - - -test('buffers', function(t) { - // have a length - var len = 16; - var list = [ new Buffer('foog'), - new Buffer('bark'), - new Buffer('bazy'), - new Buffer('kuel') ]; - - // read more than the first element. - var ret = fromList(6, { buffer: list, length: 16 }); - t.equal(ret.toString(), 'foogba'); - - // read exactly the first element. - ret = fromList(2, { buffer: list, length: 10 }); - t.equal(ret.toString(), 'rk'); - - // read less than the first element. - ret = fromList(2, { buffer: list, length: 8 }); - t.equal(ret.toString(), 'ba'); - - // read more than we have. - ret = fromList(100, { buffer: list, length: 6 }); - t.equal(ret.toString(), 'zykuel'); - - // all consumed. - t.same(list, []); - - t.end(); -}); - -test('strings', function(t) { - // have a length - var len = 16; - var list = [ 'foog', - 'bark', - 'bazy', - 'kuel' ]; - - // read more than the first element. - var ret = fromList(6, { buffer: list, length: 16, decoder: true }); - t.equal(ret, 'foogba'); - - // read exactly the first element. - ret = fromList(2, { buffer: list, length: 10, decoder: true }); - t.equal(ret, 'rk'); - - // read less than the first element. - ret = fromList(2, { buffer: list, length: 8, decoder: true }); - t.equal(ret, 'ba'); - - // read more than we have. - ret = fromList(100, { buffer: list, length: 6, decoder: true }); - t.equal(ret, 'zykuel'); - - // all consumed. - t.same(list, []); - - t.end(); -}); diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js deleted file mode 100644 index 117e253d2..000000000 --- a/test/simple/test-stream2-readable-legacy-drain.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Stream = require('stream'); -var Readable = Stream.Readable; - -var r = new Readable(); -var N = 256; -var reads = 0; -r._read = function(n) { - return r.push(++reads === N ? null : new Buffer(1)); -}; - -var rended = false; -r.on('end', function() { - rended = true; -}); - -var w = new Stream(); -w.writable = true; -var writes = 0; -var buffered = 0; -w.write = function(c) { - writes += c.length; - buffered += c.length; - process.nextTick(drain); - return false; -}; - -function drain() { - assert(buffered <= 3); - buffered = 0; - w.emit('drain'); -} - - -var wended = false; -w.end = function() { - wended = true; -}; - -// Just for kicks, let's mess with the drain count. -// This verifies that even if it gets negative in the -// pipe() cleanup function, we'll still function properly. -r.on('readable', function() { - w.emit('drain'); -}); - -r.pipe(w); -process.on('exit', function() { - assert(rended); - assert(wended); - console.error('ok'); -}); diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js deleted file mode 100644 index 65b7afda5..000000000 --- a/test/simple/test-stream2-readable-non-empty-end.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common.js'); -var Readable = require('_stream_readable'); - -var len = 0; -var chunks = new Array(10); -for (var i = 1; i <= 10; i++) { - chunks[i-1] = new Buffer(i); - len += i; -} - -var test = new Readable(); -var n = 0; -test._read = function(size) { - var chunk = chunks[n++]; - setTimeout(function() { - test.push(chunk === undefined ? null : chunk); - }); -}; - -test.on('end', thrower); -function thrower() { - throw new Error('this should not happen!'); -} - -var bytesread = 0; -test.on('readable', function() { - var b = len - bytesread - 1; - var res = test.read(b); - if (res) { - bytesread += res.length; - console.error('br=%d len=%d', bytesread, len); - setTimeout(next); - } - test.read(0); -}); -test.read(0); - -function next() { - // now let's make 'end' happen - test.removeListener('end', thrower); - - var endEmitted = false; - process.on('exit', function() { - assert(endEmitted, 'end should be emitted by now'); - }); - test.on('end', function() { - endEmitted = true; - }); - - // one to get the last byte - var r = test.read(); - assert(r); - assert.equal(r.length, 1); - r = test.read(); - assert.equal(r, null); -} diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js deleted file mode 100644 index 2e5cf25c4..000000000 --- a/test/simple/test-stream2-readable-wrap-empty.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Readable = require('_stream_readable'); -var EE = require('events').EventEmitter; - -var oldStream = new EE(); -oldStream.pause = function(){}; -oldStream.resume = function(){}; - -var newStream = new Readable().wrap(oldStream); - -var ended = false; -newStream - .on('readable', function(){}) - .on('end', function(){ ended = true; }); - -oldStream.emit('end'); - -process.on('exit', function(){ - assert.ok(ended); -}); diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js deleted file mode 100644 index 293774ca5..000000000 --- a/test/simple/test-stream2-readable-wrap.js +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); -var EE = require('events').EventEmitter; - -var testRuns = 0, completedRuns = 0; -function runTest(highWaterMark, objectMode, produce) { - testRuns++; - - var old = new EE; - var r = new Readable({ highWaterMark: highWaterMark, objectMode: objectMode }); - assert.equal(r, r.wrap(old)); - - var ended = false; - r.on('end', function() { - ended = true; - }); - - old.pause = function() { - console.error('old.pause()'); - old.emit('pause'); - flowing = false; - }; - - old.resume = function() { - console.error('old.resume()'); - old.emit('resume'); - flow(); - }; - - var flowing; - var chunks = 10; - var oldEnded = false; - var expected = []; - function flow() { - flowing = true; - while (flowing && chunks-- > 0) { - var item = produce(); - expected.push(item); - console.log('old.emit', chunks, flowing); - old.emit('data', item); - console.log('after emit', chunks, flowing); - } - if (chunks <= 0) { - oldEnded = true; - console.log('old end', chunks, flowing); - old.emit('end'); - } - } - - var w = new Writable({ highWaterMark: highWaterMark * 2, objectMode: objectMode }); - var written = []; - w._write = function(chunk, encoding, cb) { - console.log('_write', chunk); - written.push(chunk); - setTimeout(cb); - }; - - w.on('finish', function() { - completedRuns++; - performAsserts(); - }); - - r.pipe(w); - - flow(); - - function performAsserts() { - assert(ended); - assert(oldEnded); - assert.deepEqual(written, expected); - } -} - -runTest(100, false, function(){ return new Buffer(100); }); -runTest(10, false, function(){ return new Buffer('xxxxxxxxxx'); }); -runTest(1, true, function(){ return { foo: 'bar' }; }); - -var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; -runTest(1, true, function(){ return objectChunks.shift() }); - -process.on('exit', function() { - assert.equal(testRuns, completedRuns); - console.log('ok'); -}); diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js deleted file mode 100644 index 9b28e5594..000000000 --- a/test/simple/test-stream2-set-encoding.js +++ /dev/null @@ -1,367 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var assert = require('assert'); -var R = require('_stream_readable'); -var util = require('util'); - -// tiny node-tap lookalike. -var tests = []; -var count = 0; - -function test(name, fn) { - count++; - tests.push([name, fn]); -} - -function run() { - var next = tests.shift(); - if (!next) - return console.error('ok'); - - var name = next[0]; - var fn = next[1]; - console.log('# %s', name); - fn({ - same: assert.deepEqual, - equal: assert.equal, - end: function () { - count--; - run(); - } - }); -} - -// ensure all tests have run -process.on("exit", function () { - assert.equal(count, 0); -}); - -process.nextTick(run); - -///// - -util.inherits(TestReader, R); - -function TestReader(n, opts) { - R.call(this, opts); - - this.pos = 0; - this.len = n || 100; -} - -TestReader.prototype._read = function(n) { - setTimeout(function() { - - if (this.pos >= this.len) { - // double push(null) to test eos handling - this.push(null); - return this.push(null); - } - - n = Math.min(n, this.len - this.pos); - if (n <= 0) { - // double push(null) to test eos handling - this.push(null); - return this.push(null); - } - - this.pos += n; - var ret = new Buffer(n); - ret.fill('a'); - - console.log("this.push(ret)", ret) - - return this.push(ret); - }.bind(this), 1); -}; - -test('setEncoding utf8', function(t) { - var tr = new TestReader(100); - tr.setEncoding('utf8'); - var out = []; - var expect = - [ 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa' ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(10))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - - -test('setEncoding hex', function(t) { - var tr = new TestReader(100); - tr.setEncoding('hex'); - var out = []; - var expect = - [ '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161' ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(10))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - -test('setEncoding hex with read(13)', function(t) { - var tr = new TestReader(100); - tr.setEncoding('hex'); - var out = []; - var expect = - [ "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "16161" ]; - - tr.on('readable', function flow() { - console.log("readable once") - var chunk; - while (null !== (chunk = tr.read(13))) - out.push(chunk); - }); - - tr.on('end', function() { - console.log("END") - t.same(out, expect); - t.end(); - }); -}); - -test('setEncoding base64', function(t) { - var tr = new TestReader(100); - tr.setEncoding('base64'); - var out = []; - var expect = - [ 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYQ==' ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(10))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - -test('encoding: utf8', function(t) { - var tr = new TestReader(100, { encoding: 'utf8' }); - var out = []; - var expect = - [ 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa', - 'aaaaaaaaaa' ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(10))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - - -test('encoding: hex', function(t) { - var tr = new TestReader(100, { encoding: 'hex' }); - var out = []; - var expect = - [ '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161', - '6161616161' ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(10))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - -test('encoding: hex with read(13)', function(t) { - var tr = new TestReader(100, { encoding: 'hex' }); - var out = []; - var expect = - [ "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "16161" ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(13))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - -test('encoding: base64', function(t) { - var tr = new TestReader(100, { encoding: 'base64' }); - var out = []; - var expect = - [ 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYWFhYWFh', - 'YWFhYWFhYW', - 'FhYQ==' ]; - - tr.on('readable', function flow() { - var chunk; - while (null !== (chunk = tr.read(10))) - out.push(chunk); - }); - - tr.on('end', function() { - t.same(out, expect); - t.end(); - }); -}); - -test('chainable', function(t) { - var tr = new TestReader(100); - t.equal(tr.setEncoding('utf8'), tr); - t.end(); -}); diff --git a/test/simple/test-stream2-stderr-sync.js b/test/simple/test-stream2-stderr-sync.js deleted file mode 100644 index 9e2d3ec22..000000000 --- a/test/simple/test-stream2-stderr-sync.js +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Make sure that sync writes to stderr get processed before exiting. - -var common = require('../common.js'); -var assert = require('assert'); -var util = require('util'); - -var errnoException = util._errnoException; - -function parent() { - var spawn = require('child_process').spawn; - var assert = require('assert'); - var i = 0; - children.forEach(function(_, c) { - var child = spawn(process.execPath, [__filename, '' + c]); - var err = ''; - - child.stderr.on('data', function(c) { - err += c; - }); - - child.on('close', function() { - assert.equal(err, 'child ' + c + '\nfoo\nbar\nbaz\n'); - console.log('ok %d child #%d', ++i, c); - if (i === children.length) - console.log('1..' + i); - }); - }); -} - -// using console.error -function child0() { - console.error('child 0'); - console.error('foo'); - console.error('bar'); - console.error('baz'); -} - -// using process.stderr -function child1() { - process.stderr.write('child 1\n'); - process.stderr.write('foo\n'); - process.stderr.write('bar\n'); - process.stderr.write('baz\n'); -} - -// using a net socket -function child2() { - var net = require('net'); - var socket = new net.Socket({ - fd: 2, - readable: false, - writable: true}); - socket.write('child 2\n'); - socket.write('foo\n'); - socket.write('bar\n'); - socket.write('baz\n'); -} - - -function child3() { - console.error('child 3\nfoo\nbar\nbaz'); -} - -function child4() { - process.stderr.write('child 4\nfoo\nbar\nbaz\n'); -} - -var children = [ child0, child1, child2, child3, child4 ]; - -if (!process.argv[2]) { - parent(); -} else { - children[process.argv[2]](); - // immediate process.exit to kill any waiting stuff. - process.exit(); -} diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js deleted file mode 100644 index 9c9ddd8ef..000000000 --- a/test/simple/test-stream2-transform.js +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common.js'); -var PassThrough = require('_stream_passthrough'); -var Transform = require('_stream_transform'); - -// tiny node-tap lookalike. -var tests = []; -var count = 0; - -function test(name, fn) { - count++; - tests.push([name, fn]); -} - -function run() { - var next = tests.shift(); - if (!next) - return console.error('ok'); - - var name = next[0]; - var fn = next[1]; - console.log('# %s', name); - fn({ - same: assert.deepEqual, - equal: assert.equal, - ok: assert, - end: function () { - count--; - run(); - } - }); -} - -// ensure all tests have run -process.on("exit", function () { - assert.equal(count, 0); -}); - -process.nextTick(run); - -///// - -test('writable side consumption', function(t) { - var tx = new Transform({ - highWaterMark: 10 - }); - - var transformed = 0; - tx._transform = function(chunk, encoding, cb) { - transformed += chunk.length; - tx.push(chunk); - cb(); - }; - - for (var i = 1; i <= 10; i++) { - tx.write(new Buffer(i)); - } - tx.end(); - - t.equal(tx._readableState.length, 10); - t.equal(transformed, 10); - t.equal(tx._transformState.writechunk.length, 5); - t.same(tx._writableState.buffer.map(function(c) { - return c.chunk.length; - }), [6, 7, 8, 9, 10]); - - t.end(); -}); - -test('passthrough', function(t) { - var pt = new PassThrough(); - - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); - pt.end(); - - t.equal(pt.read(5).toString(), 'foogb'); - t.equal(pt.read(5).toString(), 'arkba'); - t.equal(pt.read(5).toString(), 'zykue'); - t.equal(pt.read(5).toString(), 'l'); - t.end(); -}); - -test('object passthrough', function (t) { - var pt = new PassThrough({ objectMode: true }); - - pt.write(1); - pt.write(true); - pt.write(false); - pt.write(0); - pt.write('foo'); - pt.write(''); - pt.write({ a: 'b'}); - pt.end(); - - t.equal(pt.read(), 1); - t.equal(pt.read(), true); - t.equal(pt.read(), false); - t.equal(pt.read(), 0); - t.equal(pt.read(), 'foo'); - t.equal(pt.read(), ''); - t.same(pt.read(), { a: 'b'}); - t.end(); -}); - -test('simple transform', function(t) { - var pt = new Transform; - pt._transform = function(c, e, cb) { - var ret = new Buffer(c.length); - ret.fill('x'); - pt.push(ret); - cb(); - }; - - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); - pt.end(); - - t.equal(pt.read(5).toString(), 'xxxxx'); - t.equal(pt.read(5).toString(), 'xxxxx'); - t.equal(pt.read(5).toString(), 'xxxxx'); - t.equal(pt.read(5).toString(), 'x'); - t.end(); -}); - -test('simple object transform', function(t) { - var pt = new Transform({ objectMode: true }); - pt._transform = function(c, e, cb) { - pt.push(JSON.stringify(c)); - cb(); - }; - - pt.write(1); - pt.write(true); - pt.write(false); - pt.write(0); - pt.write('foo'); - pt.write(''); - pt.write({ a: 'b'}); - pt.end(); - - t.equal(pt.read(), '1'); - t.equal(pt.read(), 'true'); - t.equal(pt.read(), 'false'); - t.equal(pt.read(), '0'); - t.equal(pt.read(), '"foo"'); - t.equal(pt.read(), '""'); - t.equal(pt.read(), '{"a":"b"}'); - t.end(); -}); - -test('async passthrough', function(t) { - var pt = new Transform; - pt._transform = function(chunk, encoding, cb) { - setTimeout(function() { - pt.push(chunk); - cb(); - }, 10); - }; - - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); - pt.end(); - - pt.on('finish', function() { - t.equal(pt.read(5).toString(), 'foogb'); - t.equal(pt.read(5).toString(), 'arkba'); - t.equal(pt.read(5).toString(), 'zykue'); - t.equal(pt.read(5).toString(), 'l'); - t.end(); - }); -}); - -test('assymetric transform (expand)', function(t) { - var pt = new Transform; - - // emit each chunk 2 times. - pt._transform = function(chunk, encoding, cb) { - setTimeout(function() { - pt.push(chunk); - setTimeout(function() { - pt.push(chunk); - cb(); - }, 10) - }, 10); - }; - - pt.write(new Buffer('foog')); - pt.write(new Buffer('bark')); - pt.write(new Buffer('bazy')); - pt.write(new Buffer('kuel')); - pt.end(); - - pt.on('finish', function() { - t.equal(pt.read(5).toString(), 'foogf'); - t.equal(pt.read(5).toString(), 'oogba'); - t.equal(pt.read(5).toString(), 'rkbar'); - t.equal(pt.read(5).toString(), 'kbazy'); - t.equal(pt.read(5).toString(), 'bazyk'); - t.equal(pt.read(5).toString(), 'uelku'); - t.equal(pt.read(5).toString(), 'el'); - t.end(); - }); -}); - -test('assymetric transform (compress)', function(t) { - var pt = new Transform; - - // each output is the first char of 3 consecutive chunks, - // or whatever's left. - pt.state = ''; - - pt._transform = function(chunk, encoding, cb) { - if (!chunk) - chunk = ''; - var s = chunk.toString(); - setTimeout(function() { - this.state += s.charAt(0); - if (this.state.length === 3) { - pt.push(new Buffer(this.state)); - this.state = ''; - } - cb(); - }.bind(this), 10); - }; - - pt._flush = function(cb) { - // just output whatever we have. - pt.push(new Buffer(this.state)); - this.state = ''; - cb(); - }; - - pt.write(new Buffer('aaaa')); - pt.write(new Buffer('bbbb')); - pt.write(new Buffer('cccc')); - pt.write(new Buffer('dddd')); - pt.write(new Buffer('eeee')); - pt.write(new Buffer('aaaa')); - pt.write(new Buffer('bbbb')); - pt.write(new Buffer('cccc')); - pt.write(new Buffer('dddd')); - pt.write(new Buffer('eeee')); - pt.write(new Buffer('aaaa')); - pt.write(new Buffer('bbbb')); - pt.write(new Buffer('cccc')); - pt.write(new Buffer('dddd')); - pt.end(); - - // 'abcdeabcdeabcd' - pt.on('finish', function() { - t.equal(pt.read(5).toString(), 'abcde'); - t.equal(pt.read(5).toString(), 'abcde'); - t.equal(pt.read(5).toString(), 'abcd'); - t.end(); - }); -}); - -// this tests for a stall when data is written to a full stream -// that has empty transforms. -test('complex transform', function(t) { - var count = 0; - var saved = null; - var pt = new Transform({highWaterMark:3}); - pt._transform = function(c, e, cb) { - if (count++ === 1) - saved = c; - else { - if (saved) { - pt.push(saved); - saved = null; - } - pt.push(c); - } - - cb(); - }; - - pt.once('readable', function() { - process.nextTick(function() { - pt.write(new Buffer('d')); - pt.write(new Buffer('ef'), function() { - pt.end(); - t.end(); - }); - t.equal(pt.read().toString(), 'abcdef'); - t.equal(pt.read(), null); - }); - }); - - pt.write(new Buffer('abc')); -}); - - -test('passthrough event emission', function(t) { - var pt = new PassThrough(); - var emits = 0; - pt.on('readable', function() { - var state = pt._readableState; - console.error('>>> emit readable %d', emits); - emits++; - }); - - var i = 0; - - pt.write(new Buffer('foog')); - - console.error('need emit 0'); - pt.write(new Buffer('bark')); - - console.error('should have emitted readable now 1 === %d', emits); - t.equal(emits, 1); - - t.equal(pt.read(5).toString(), 'foogb'); - t.equal(pt.read(5) + '', 'null'); - - console.error('need emit 1'); - - pt.write(new Buffer('bazy')); - console.error('should have emitted, but not again'); - pt.write(new Buffer('kuel')); - - console.error('should have emitted readable now 2 === %d', emits); - t.equal(emits, 2); - - t.equal(pt.read(5).toString(), 'arkba'); - t.equal(pt.read(5).toString(), 'zykue'); - t.equal(pt.read(5), null); - - console.error('need emit 2'); - - pt.end(); - - t.equal(emits, 3); - - t.equal(pt.read(5).toString(), 'l'); - t.equal(pt.read(5), null); - - console.error('should not have emitted again'); - t.equal(emits, 3); - t.end(); -}); - -test('passthrough event emission reordered', function(t) { - var pt = new PassThrough; - var emits = 0; - pt.on('readable', function() { - console.error('emit readable', emits) - emits++; - }); - - pt.write(new Buffer('foog')); - console.error('need emit 0'); - pt.write(new Buffer('bark')); - console.error('should have emitted readable now 1 === %d', emits); - t.equal(emits, 1); - - t.equal(pt.read(5).toString(), 'foogb'); - t.equal(pt.read(5), null); - - console.error('need emit 1'); - pt.once('readable', function() { - t.equal(pt.read(5).toString(), 'arkba'); - - t.equal(pt.read(5), null); - - console.error('need emit 2'); - pt.once('readable', function() { - t.equal(pt.read(5).toString(), 'zykue'); - t.equal(pt.read(5), null); - pt.once('readable', function() { - t.equal(pt.read(5).toString(), 'l'); - t.equal(pt.read(5), null); - t.equal(emits, 4); - t.end(); - }); - pt.end(); - }); - pt.write(new Buffer('kuel')); - }); - - pt.write(new Buffer('bazy')); -}); - -test('passthrough facaded', function(t) { - console.error('passthrough facaded'); - var pt = new PassThrough; - var datas = []; - pt.on('data', function(chunk) { - datas.push(chunk.toString()); - }); - - pt.on('end', function() { - t.same(datas, ['foog', 'bark', 'bazy', 'kuel']); - t.end(); - }); - - pt.write(new Buffer('foog')); - setTimeout(function() { - pt.write(new Buffer('bark')); - setTimeout(function() { - pt.write(new Buffer('bazy')); - setTimeout(function() { - pt.write(new Buffer('kuel')); - setTimeout(function() { - pt.end(); - }, 10); - }, 10); - }, 10); - }, 10); -}); - -test('object transform (json parse)', function(t) { - console.error('json parse stream'); - var jp = new Transform({ objectMode: true }); - jp._transform = function(data, encoding, cb) { - try { - jp.push(JSON.parse(data)); - cb(); - } catch (er) { - cb(er); - } - }; - - // anything except null/undefined is fine. - // those are "magic" in the stream API, because they signal EOF. - var objects = [ - { foo: 'bar' }, - 100, - "string", - { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } - ]; - - var ended = false; - jp.on('end', function() { - ended = true; - }); - - objects.forEach(function(obj) { - jp.write(JSON.stringify(obj)); - var res = jp.read(); - t.same(res, obj); - }); - - jp.end(); - // read one more time to get the 'end' event - jp.read(); - - process.nextTick(function() { - t.ok(ended); - t.end(); - }) -}); - -test('object transform (json stringify)', function(t) { - console.error('json parse stream'); - var js = new Transform({ objectMode: true }); - js._transform = function(data, encoding, cb) { - try { - js.push(JSON.stringify(data)); - cb(); - } catch (er) { - cb(er); - } - }; - - // anything except null/undefined is fine. - // those are "magic" in the stream API, because they signal EOF. - var objects = [ - { foo: 'bar' }, - 100, - "string", - { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } - ]; - - var ended = false; - js.on('end', function() { - ended = true; - }); - - objects.forEach(function(obj) { - js.write(obj); - var res = js.read(); - t.equal(res, JSON.stringify(obj)); - }); - - js.end(); - // read one more time to get the 'end' event - js.read(); - - process.nextTick(function() { - t.ok(ended); - t.end(); - }) -}); diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js deleted file mode 100644 index d66dc3cbe..000000000 --- a/test/simple/test-stream2-unpipe-drain.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var assert = require('assert'); -var stream = require('stream'); -var crypto = require('crypto'); - -var util = require('util'); - -function TestWriter() { - stream.Writable.call(this); -} -util.inherits(TestWriter, stream.Writable); - -TestWriter.prototype._write = function (buffer, encoding, callback) { - console.log('write called'); - // super slow write stream (callback never called) -}; - -var dest = new TestWriter(); - -function TestReader(id) { - stream.Readable.call(this); - this.reads = 0; -} -util.inherits(TestReader, stream.Readable); - -TestReader.prototype._read = function (size) { - this.reads += 1; - this.push(crypto.randomBytes(size)); -}; - -var src1 = new TestReader(); -var src2 = new TestReader(); - -src1.pipe(dest); - -src1.once('readable', function () { - process.nextTick(function () { - - src2.pipe(dest); - - src2.once('readable', function () { - process.nextTick(function () { - - src1.unpipe(dest); - }); - }); - }); -}); - - -process.on('exit', function () { - assert.equal(src1.reads, 2); - assert.equal(src2.reads, 2); -}); diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js deleted file mode 100644 index 99f8746c4..000000000 --- a/test/simple/test-stream2-unpipe-leak.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common.js'); -var assert = require('assert'); -var stream = require('stream'); - -var chunk = new Buffer('hallo'); - -var util = require('util'); - -function TestWriter() { - stream.Writable.call(this); -} -util.inherits(TestWriter, stream.Writable); - -TestWriter.prototype._write = function(buffer, encoding, callback) { - callback(null); -}; - -var dest = new TestWriter(); - -// Set this high so that we'd trigger a nextTick warning -// and/or RangeError if we do maybeReadMore wrong. -function TestReader() { - stream.Readable.call(this, { highWaterMark: 0x10000 }); -} -util.inherits(TestReader, stream.Readable); - -TestReader.prototype._read = function(size) { - this.push(chunk); -}; - -var src = new TestReader(); - -for (var i = 0; i < 10; i++) { - src.pipe(dest); - src.unpipe(dest); -} - -assert.equal(src.listeners('end').length, 0); -assert.equal(src.listeners('readable').length, 0); - -assert.equal(dest.listeners('unpipe').length, 0); -assert.equal(dest.listeners('drain').length, 0); -assert.equal(dest.listeners('error').length, 0); -assert.equal(dest.listeners('close').length, 0); -assert.equal(dest.listeners('finish').length, 0); - -console.error(src._readableState); -process.on('exit', function() { - src._readableState.buffer.length = 0; - console.error(src._readableState); - assert(src._readableState.length >= src._readableState.highWaterMark); - console.log('ok'); -}); diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js deleted file mode 100644 index 3767ce140..000000000 --- a/test/simple/test-stream2-writable.js +++ /dev/null @@ -1,405 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var W = require('_stream_writable'); -var D = require('_stream_duplex'); -var assert = require('assert'); - -var util = require('util'); -util.inherits(TestWriter, W); - -function TestWriter() { - W.apply(this, arguments); - this.buffer = []; - this.written = 0; -} - -TestWriter.prototype._write = function(chunk, encoding, cb) { - // simulate a small unpredictable latency - setTimeout(function() { - this.buffer.push(chunk.toString()); - this.written += chunk.length; - cb(); - }.bind(this), Math.floor(Math.random() * 10)); -}; - -var chunks = new Array(50); -for (var i = 0; i < chunks.length; i++) { - chunks[i] = new Array(i + 1).join('x'); -} - -// tiny node-tap lookalike. -var tests = []; -var count = 0; - -function test(name, fn) { - count++; - tests.push([name, fn]); -} - -function run() { - var next = tests.shift(); - if (!next) - return console.error('ok'); - - var name = next[0]; - var fn = next[1]; - console.log('# %s', name); - fn({ - same: assert.deepEqual, - equal: assert.equal, - end: function () { - count--; - run(); - } - }); -} - -// ensure all tests have run -process.on("exit", function () { - assert.equal(count, 0); -}); - -process.nextTick(run); - -test('write fast', function(t) { - var tw = new TestWriter({ - highWaterMark: 100 - }); - - tw.on('finish', function() { - t.same(tw.buffer, chunks, 'got chunks in the right order'); - t.end(); - }); - - chunks.forEach(function(chunk) { - // screw backpressure. Just buffer it all up. - tw.write(chunk); - }); - tw.end(); -}); - -test('write slow', function(t) { - var tw = new TestWriter({ - highWaterMark: 100 - }); - - tw.on('finish', function() { - t.same(tw.buffer, chunks, 'got chunks in the right order'); - t.end(); - }); - - var i = 0; - (function W() { - tw.write(chunks[i++]); - if (i < chunks.length) - setTimeout(W, 10); - else - tw.end(); - })(); -}); - -test('write backpressure', function(t) { - var tw = new TestWriter({ - highWaterMark: 50 - }); - - var drains = 0; - - tw.on('finish', function() { - t.same(tw.buffer, chunks, 'got chunks in the right order'); - t.equal(drains, 17); - t.end(); - }); - - tw.on('drain', function() { - drains++; - }); - - var i = 0; - (function W() { - do { - var ret = tw.write(chunks[i++]); - } while (ret !== false && i < chunks.length); - - if (i < chunks.length) { - assert(tw._writableState.length >= 50); - tw.once('drain', W); - } else { - tw.end(); - } - })(); -}); - -test('write bufferize', function(t) { - var tw = new TestWriter({ - highWaterMark: 100 - }); - - var encodings = - [ 'hex', - 'utf8', - 'utf-8', - 'ascii', - 'binary', - 'base64', - 'ucs2', - 'ucs-2', - 'utf16le', - 'utf-16le', - undefined ]; - - tw.on('finish', function() { - t.same(tw.buffer, chunks, 'got the expected chunks'); - }); - - chunks.forEach(function(chunk, i) { - var enc = encodings[ i % encodings.length ]; - chunk = new Buffer(chunk); - tw.write(chunk.toString(enc), enc); - }); - t.end(); -}); - -test('write no bufferize', function(t) { - var tw = new TestWriter({ - highWaterMark: 100, - decodeStrings: false - }); - - tw._write = function(chunk, encoding, cb) { - assert(typeof chunk === 'string'); - chunk = new Buffer(chunk, encoding); - return TestWriter.prototype._write.call(this, chunk, encoding, cb); - }; - - var encodings = - [ 'hex', - 'utf8', - 'utf-8', - 'ascii', - 'binary', - 'base64', - 'ucs2', - 'ucs-2', - 'utf16le', - 'utf-16le', - undefined ]; - - tw.on('finish', function() { - t.same(tw.buffer, chunks, 'got the expected chunks'); - }); - - chunks.forEach(function(chunk, i) { - var enc = encodings[ i % encodings.length ]; - chunk = new Buffer(chunk); - tw.write(chunk.toString(enc), enc); - }); - t.end(); -}); - -test('write callbacks', function (t) { - var callbacks = chunks.map(function(chunk, i) { - return [i, function(er) { - callbacks._called[i] = chunk; - }]; - }).reduce(function(set, x) { - set['callback-' + x[0]] = x[1]; - return set; - }, {}); - callbacks._called = []; - - var tw = new TestWriter({ - highWaterMark: 100 - }); - - tw.on('finish', function() { - process.nextTick(function() { - t.same(tw.buffer, chunks, 'got chunks in the right order'); - t.same(callbacks._called, chunks, 'called all callbacks'); - t.end(); - }); - }); - - chunks.forEach(function(chunk, i) { - tw.write(chunk, callbacks['callback-' + i]); - }); - tw.end(); -}); - -test('end callback', function (t) { - var tw = new TestWriter(); - tw.end(function () { - t.end(); - }); -}); - -test('end callback with chunk', function (t) { - var tw = new TestWriter(); - tw.end(new Buffer('hello world'), function () { - t.end(); - }); -}); - -test('end callback with chunk and encoding', function (t) { - var tw = new TestWriter(); - tw.end('hello world', 'ascii', function () { - t.end(); - }); -}); - -test('end callback after .write() call', function (t) { - var tw = new TestWriter(); - tw.write(new Buffer('hello world')); - tw.end(function () { - t.end(); - }); -}); - -test('end callback called after write callback', function (t) { - var tw = new TestWriter(); - var writeCalledback = false; - tw.write(new Buffer('hello world'), function() { - writeCalledback = true; - }); - tw.end(function () { - t.equal(writeCalledback, true); - t.end(); - }); -}); - -test('encoding should be ignored for buffers', function(t) { - var tw = new W(); - var hex = '018b5e9a8f6236ffe30e31baf80d2cf6eb'; - tw._write = function(chunk, encoding, cb) { - t.equal(chunk.toString('hex'), hex); - t.end(); - }; - var buf = new Buffer(hex, 'hex'); - tw.write(buf, 'binary'); -}); - -test('writables are not pipable', function(t) { - var w = new W(); - w._write = function() {}; - var gotError = false; - w.on('error', function(er) { - gotError = true; - }); - w.pipe(process.stdout); - assert(gotError); - t.end(); -}); - -test('duplexes are pipable', function(t) { - var d = new D(); - d._read = function() {}; - d._write = function() {}; - var gotError = false; - d.on('error', function(er) { - gotError = true; - }); - d.pipe(process.stdout); - assert(!gotError); - t.end(); -}); - -test('end(chunk) two times is an error', function(t) { - var w = new W(); - w._write = function() {}; - var gotError = false; - w.on('error', function(er) { - gotError = true; - t.equal(er.message, 'write after end'); - }); - w.end('this is the end'); - w.end('and so is this'); - process.nextTick(function() { - assert(gotError); - t.end(); - }); -}); - -test('dont end while writing', function(t) { - var w = new W(); - var wrote = false; - w._write = function(chunk, e, cb) { - assert(!this.writing); - wrote = true; - this.writing = true; - setTimeout(function() { - this.writing = false; - cb(); - }); - }; - w.on('finish', function() { - assert(wrote); - t.end(); - }); - w.write(Buffer(0)); - w.end(); -}); - -test('finish does not come before write cb', function(t) { - var w = new W(); - var writeCb = false; - w._write = function(chunk, e, cb) { - setTimeout(function() { - writeCb = true; - cb(); - }, 10); - }; - w.on('finish', function() { - assert(writeCb); - t.end(); - }); - w.write(Buffer(0)); - w.end(); -}); - -test('finish does not come before sync _write cb', function(t) { - var w = new W(); - var writeCb = false; - w._write = function(chunk, e, cb) { - cb(); - }; - w.on('finish', function() { - assert(writeCb); - t.end(); - }); - w.write(Buffer(0), function(er) { - writeCb = true; - }); - w.end(); -}); - -test('finish is emitted if last chunk is empty', function(t) { - var w = new W(); - w._write = function(chunk, e, cb) { - process.nextTick(cb); - }; - w.on('finish', function() { - t.end(); - }); - w.write(Buffer(1)); - w.end(Buffer(0)); -}); diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js deleted file mode 100644 index b91bde3f0..000000000 --- a/test/simple/test-stream3-pause-then-read.js +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var stream = require('stream'); -var Readable = stream.Readable; -var Writable = stream.Writable; - -var totalChunks = 100; -var chunkSize = 99; -var expectTotalData = totalChunks * chunkSize; -var expectEndingData = expectTotalData; - -var r = new Readable({ highWaterMark: 1000 }); -var chunks = totalChunks; -r._read = function(n) { - if (!(chunks % 2)) - setImmediate(push); - else if (!(chunks % 3)) - process.nextTick(push); - else - push(); -}; - -var totalPushed = 0; -function push() { - var chunk = chunks-- > 0 ? new Buffer(chunkSize) : null; - if (chunk) { - totalPushed += chunk.length; - chunk.fill('x'); - } - r.push(chunk); -} - -read100(); - -// first we read 100 bytes -function read100() { - readn(100, onData); -} - -function readn(n, then) { - console.error('read %d', n); - expectEndingData -= n; - ;(function read() { - var c = r.read(n); - if (!c) - r.once('readable', read); - else { - assert.equal(c.length, n); - assert(!r._readableState.flowing); - then(); - } - })(); -} - -// then we listen to some data events -function onData() { - expectEndingData -= 100; - console.error('onData'); - var seen = 0; - r.on('data', function od(c) { - seen += c.length; - if (seen >= 100) { - // seen enough - r.removeListener('data', od); - r.pause(); - if (seen > 100) { - // oh no, seen too much! - // put the extra back. - var diff = seen - 100; - r.unshift(c.slice(c.length - diff)); - console.error('seen too much', seen, diff); - } - - // Nothing should be lost in between - setImmediate(pipeLittle); - } - }); -} - -// Just pipe 200 bytes, then unshift the extra and unpipe -function pipeLittle() { - expectEndingData -= 200; - console.error('pipe a little'); - var w = new Writable(); - var written = 0; - w.on('finish', function() { - assert.equal(written, 200); - setImmediate(read1234); - }); - w._write = function(chunk, encoding, cb) { - written += chunk.length; - if (written >= 200) { - r.unpipe(w); - w.end(); - cb(); - if (written > 200) { - var diff = written - 200; - written -= diff; - r.unshift(chunk.slice(chunk.length - diff)); - } - } else { - setImmediate(cb); - } - }; - r.pipe(w); -} - -// now read 1234 more bytes -function read1234() { - readn(1234, resumePause); -} - -function resumePause() { - console.error('resumePause'); - // don't read anything, just resume and re-pause a whole bunch - r.resume(); - r.pause(); - r.resume(); - r.pause(); - r.resume(); - r.pause(); - r.resume(); - r.pause(); - r.resume(); - r.pause(); - setImmediate(pipe); -} - - -function pipe() { - console.error('pipe the rest'); - var w = new Writable(); - var written = 0; - w._write = function(chunk, encoding, cb) { - written += chunk.length; - cb(); - }; - w.on('finish', function() { - console.error('written', written, totalPushed); - assert.equal(written, expectEndingData); - assert.equal(totalPushed, expectTotalData); - console.log('ok'); - }); - r.pipe(w); -} diff --git a/test/simple/test-string-decoder-end.js b/test/simple/test-string-decoder-end.js deleted file mode 100644 index fea55d410..000000000 --- a/test/simple/test-string-decoder-end.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// verify that the string decoder works getting 1 byte at a time, -// the whole buffer at once, and that both match the .toString(enc) -// result of the entire buffer. - -var assert = require('assert'); -var SD = require('string_decoder').StringDecoder; -var encodings = ['base64', 'hex', 'utf8', 'utf16le', 'ucs2']; - -var bufs = [ '☃💩', 'asdf' ].map(function(b) { - return new Buffer(b); -}); - -// also test just arbitrary bytes from 0-15. -for (var i = 1; i <= 16; i++) { - var bytes = new Array(i).join('.').split('.').map(function(_, j) { - return j + 0x78; - }); - bufs.push(new Buffer(bytes)); -} - -encodings.forEach(testEncoding); - -console.log('ok'); - -function testEncoding(encoding) { - bufs.forEach(function(buf) { - testBuf(encoding, buf); - }); -} - -function testBuf(encoding, buf) { - console.error('# %s', encoding, buf); - - // write one byte at a time. - var s = new SD(encoding); - var res1 = ''; - for (var i = 0; i < buf.length; i++) { - res1 += s.write(buf.slice(i, i + 1)); - } - res1 += s.end(); - - // write the whole buffer at once. - var res2 = ''; - var s = new SD(encoding); - res2 += s.write(buf); - res2 += s.end(); - - // .toString() on the buffer - var res3 = buf.toString(encoding); - - console.log('expect=%j', res3); - assert.equal(res1, res3, 'one byte at a time should match toString'); - assert.equal(res2, res3, 'all bytes at once should match toString'); -} diff --git a/test/simple/test-string-decoder.js b/test/simple/test-string-decoder.js deleted file mode 100644 index 9f47d131b..000000000 --- a/test/simple/test-string-decoder.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var StringDecoder = require('string_decoder').StringDecoder; - -process.stdout.write('scanning '); - -// UTF-8 -test('utf-8', new Buffer('$', 'utf-8'), '$'); -test('utf-8', new Buffer('¢', 'utf-8'), '¢'); -test('utf-8', new Buffer('€', 'utf-8'), '€'); -test('utf-8', new Buffer('𤭢', 'utf-8'), '𤭢'); -// A mixed ascii and non-ascii string -// Test stolen from deps/v8/test/cctest/test-strings.cc -// U+02E4 -> CB A4 -// U+0064 -> 64 -// U+12E4 -> E1 8B A4 -// U+0030 -> 30 -// U+3045 -> E3 81 85 -test( - 'utf-8', - new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), - '\u02e4\u0064\u12e4\u0030\u3045' -); - -// CESU-8 -test('utf-8', new Buffer('EDA0BDEDB18D', 'hex'), '\ud83d\udc4d'); // thumbs up - -// UCS-2 -test('ucs2', new Buffer('ababc', 'ucs2'), 'ababc'); - -// UTF-16LE -test('ucs2', new Buffer('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up - -console.log(' crayon!'); - -// test verifies that StringDecoder will correctly decode the given input -// buffer with the given encoding to the expected output. It will attempt all -// possible ways to write() the input buffer, see writeSequences(). The -// singleSequence allows for easy debugging of a specific sequence which is -// useful in case of test failures. -function test(encoding, input, expected, singleSequence) { - var sequences; - if (!singleSequence) { - sequences = writeSequences(input.length); - } else { - sequences = [singleSequence]; - } - sequences.forEach(function(sequence) { - var decoder = new StringDecoder(encoding); - var output = ''; - sequence.forEach(function(write) { - output += decoder.write(input.slice(write[0], write[1])); - }); - process.stdout.write('.'); - if (output !== expected) { - var message = - 'Expected "'+unicodeEscape(expected)+'", '+ - 'but got "'+unicodeEscape(output)+'"\n'+ - 'Write sequence: '+JSON.stringify(sequence)+'\n'+ - 'Decoder charBuffer: 0x'+decoder.charBuffer.toString('hex')+'\n'+ - 'Full Decoder State: '+JSON.stringify(decoder, null, 2); - assert.fail(output, expected, message); - } - }); -} - -// unicodeEscape prints the str contents as unicode escape codes. -function unicodeEscape(str) { - var r = ''; - for (var i = 0; i < str.length; i++) { - r += '\\u'+str.charCodeAt(i).toString(16); - } - return r; -} - -// writeSequences returns an array of arrays that describes all possible ways a -// buffer of the given length could be split up and passed to sequential write -// calls. -// -// e.G. writeSequences(3) will return: [ -// [ [ 0, 3 ] ], -// [ [ 0, 2 ], [ 2, 3 ] ], -// [ [ 0, 1 ], [ 1, 3 ] ], -// [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ] -// ] -function writeSequences(length, start, sequence) { - if (start === undefined) { - start = 0; - sequence = [] - } else if (start === length) { - return [sequence]; - } - var sequences = []; - for (var end = length; end > start; end--) { - var subSequence = sequence.concat([[start, end]]); - var subSequences = writeSequences(length, end, subSequence, sequences); - sequences = sequences.concat(subSequences); - } - return sequences; -} - diff --git a/test/simple/test-stringbytes-external.js b/test/simple/test-stringbytes-external.js deleted file mode 100644 index c7c716c83..000000000 --- a/test/simple/test-stringbytes-external.js +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -// minimum string size to overflow into external string space -var EXTERN_APEX = 0xFBEE9; - -// manually controlled string for checking binary output -var ucs2_control = 'a\u0000'; -var write_str = 'a'; - - -// first do basic checks -var b = new Buffer(write_str, 'ucs2'); -var c = b.toString('binary'); -assert.equal(b[0], 0x61); -assert.equal(b[1], 0); -assert.equal(ucs2_control, c); - - -// grow the strings to proper length -while (write_str.length <= EXTERN_APEX) { - write_str += write_str; - ucs2_control += ucs2_control; -} -write_str += write_str.substr(0, EXTERN_APEX - write_str.length); -ucs2_control += ucs2_control.substr(0, EXTERN_APEX * 2 - ucs2_control.length); - - -// check resultant buffer and output string -var b = new Buffer(write_str, 'ucs2'); -// check fist Buffer created from write string -for (var i = 0; i < b.length; i += 2) { - assert.equal(b[i], 0x61); - assert.equal(b[i + 1], 0); -} -// create another string to create an external string -var b_bin = b.toString('binary'); -var b_ucs = b.toString('ucs2'); -// check control against external binary string -assert.equal(ucs2_control, b_bin); -// create buffer copy from external -var c_bin = new Buffer(b_bin, 'binary'); -var c_ucs = new Buffer(b_ucs, 'ucs2'); -// make sure they're the same length -assert.equal(c_bin.length, c_ucs.length); -// make sure Buffers from externals are the same -for (var i = 0; i < c_bin.length; i++) { - assert.equal(c_bin[i], c_ucs[i], c_bin[i] + ' == ' + c_ucs[i] + - ' : index ' + i); -} -// check resultant strings -assert.equal(c_bin.toString('ucs2'), c_ucs.toString('ucs2')); -assert.equal(c_bin.toString('binary'), ucs2_control); -assert.equal(c_ucs.toString('binary'), ucs2_control); - - - -// now let's test BASE64 and HEX ecoding/decoding -var RADIOS = 2; -var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; -var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; - -(function () { - for (var j = 0; j < RADIOS * 2; j += 1) { - var datum = b; - var slice = datum.slice(0, PRE_HALF_APEX + j); - var slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); - var pumped_string = slice.toString('hex'); - var pumped_string2 = slice2.toString('hex'); - var decoded = new Buffer(pumped_string, 'hex'); - - var metadata = "\nEXTERN_APEX=1031913 - pumped_string.length=" - metadata += pumped_string.length + '\n'; - - // the string are the same? - for (var k = 0; k < pumped_string.length; ++k) { - assert.equal(pumped_string[k], pumped_string2[k], - metadata + 'chars should be the same at ' + k); - } - - // the recoded buffer is the same? - for (var i = 0; i < decoded.length; ++i) { - assert.equal(datum[i], decoded[i], - metadata + 'bytes should be the same at ' + i); - } - } -})(); - -(function () { - for (var j = 0; j < RADIOS * 2; j += 1) { - var datum = b; - var slice = datum.slice(0, PRE_3OF4_APEX + j); - var slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); - var pumped_string = slice.toString('base64'); - var pumped_string2 = slice2.toString('base64'); - var decoded = new Buffer(pumped_string, 'base64'); - - var metadata = "\nEXTERN_APEX=1031913 - data=" + slice.length - metadata += " pumped_string.length=" + pumped_string.length + '\n'; - - // the string are the same? - for (var k = 0; k < pumped_string.length - 3; ++k) { - assert.equal(pumped_string[k], pumped_string2[k], - metadata + 'chars should be the same for two slices at ' - + k + ' ' + pumped_string[k] + ' ' + pumped_string2[k]); - } - - // the recoded buffer is the same? - for (var i = 0; i < decoded.length; ++i) { - assert.equal(datum[i], decoded[i], - metadata + 'bytes should be the same at ' + i); - } - } -})(); diff --git a/test/simple/test-sync-fileread.js b/test/simple/test-sync-fileread.js deleted file mode 100644 index 428838a8c..000000000 --- a/test/simple/test-sync-fileread.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var fs = require('fs'); - -var fixture = path.join(__dirname, '../fixtures/x.txt'); - -assert.equal('xyz\n', fs.readFileSync(fixture)); diff --git a/test/simple/test-sys.js b/test/simple/test-sys.js deleted file mode 100644 index 6ea33161c..000000000 --- a/test/simple/test-sys.js +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -assert.equal('0', common.inspect(0)); -assert.equal('1', common.inspect(1)); -assert.equal('false', common.inspect(false)); -assert.equal("''", common.inspect('')); -assert.equal("'hello'", common.inspect('hello')); -assert.equal('[Function]', common.inspect(function() {})); -assert.equal('undefined', common.inspect(undefined)); -assert.equal('null', common.inspect(null)); -assert.equal('/foo(bar\\n)?/gi', common.inspect(/foo(bar\n)?/gi)); -assert.equal(new Date('2010-02-14T12:48:40+01:00').toString(), - common.inspect(new Date('Sun, 14 Feb 2010 11:48:40 GMT'))); - -assert.equal("'\\n\\u0001'", common.inspect('\n\u0001')); - -assert.equal('[]', common.inspect([])); -assert.equal('{}', common.inspect(Object.create([]))); -assert.equal('[ 1, 2 ]', common.inspect([1, 2])); -assert.equal('[ 1, [ 2, 3 ] ]', common.inspect([1, [2, 3]])); - -assert.equal('{}', common.inspect({})); -assert.equal('{ a: 1 }', common.inspect({a: 1})); -assert.equal('{ a: [Function] }', common.inspect({a: function() {}})); -assert.equal('{ a: 1, b: 2 }', common.inspect({a: 1, b: 2})); -assert.equal('{ a: {} }', common.inspect({'a': {}})); -assert.equal('{ a: { b: 2 } }', common.inspect({'a': {'b': 2}})); -assert.equal('{ a: { b: { c: [Object] } } }', - common.inspect({'a': {'b': { 'c': { 'd': 2 }}}})); -assert.equal('{ a: { b: { c: { d: 2 } } } }', - common.inspect({'a': {'b': { 'c': { 'd': 2 }}}}, false, null)); -assert.equal('[ 1, 2, 3, [length]: 3 ]', common.inspect([1, 2, 3], true)); -assert.equal('{ a: [Object] }', - common.inspect({'a': {'b': { 'c': 2}}}, false, 0)); -assert.equal('{ a: { b: [Object] } }', - common.inspect({'a': {'b': { 'c': 2}}}, false, 1)); -assert.equal('{ visible: 1 }', - common.inspect(Object.create({}, - {visible: {value: 1, enumerable: true}, hidden: {value: 2}})) -); - -// Due to the hash seed randomization it's not deterministic the order that -// the following ways this hash is displayed. -// See http://codereview.chromium.org/9124004/ - -var out = common.inspect(Object.create({}, - {visible: {value: 1, enumerable: true}, hidden: {value: 2}}), true); -if (out !== '{ [hidden]: 2, visible: 1 }' && - out !== '{ visible: 1, [hidden]: 2 }') { - assert.ok(false); -} - - -// Objects without prototype -var out = common.inspect(Object.create(null, - { name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}}), true); -if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && - out !== "{ name: 'Tim', [hidden]: 'secret' }") { - assert(false); -} - - -assert.equal('{ name: \'Tim\' }', - common.inspect(Object.create(null, - {name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}})) -); - - -// Dynamic properties -assert.equal('{ readonly: [Getter] }', - common.inspect({get readonly() {}})); - -assert.equal('{ readwrite: [Getter/Setter] }', - common.inspect({get readwrite() {},set readwrite(val) {}})); - -assert.equal('{ writeonly: [Setter] }', - common.inspect({set writeonly(val) {}})); - -var value = {}; -value['a'] = value; -assert.equal('{ a: [Circular] }', common.inspect(value)); - -// Array with dynamic properties -value = [1, 2, 3]; -value.__defineGetter__('growingLength', function() { - this.push(true); return this.length; -}); -assert.equal('[ 1, 2, 3, growingLength: [Getter] ]', common.inspect(value)); - -// Function with properties -value = function() {}; -value.aprop = 42; -assert.equal('{ [Function] aprop: 42 }', common.inspect(value)); - -// Regular expressions with properties -value = /123/ig; -value.aprop = 42; -assert.equal('{ /123/gi aprop: 42 }', common.inspect(value)); - -// Dates with properties -value = new Date('Sun, 14 Feb 2010 11:48:40 GMT'); -value.aprop = 42; -assert.equal('{ Sun, 14 Feb 2010 11:48:40 GMT aprop: 42 }', - common.inspect(value) -); diff --git a/test/simple/test-tcp-wrap-connect.js b/test/simple/test-tcp-wrap-connect.js deleted file mode 100644 index 9e915d243..000000000 --- a/test/simple/test-tcp-wrap-connect.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var TCP = process.binding('tcp_wrap').TCP; -var TCPConnectWrap = process.binding('tcp_wrap').TCPConnectWrap; -var ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; - -function makeConnection() { - var client = new TCP(); - - var req = new TCPConnectWrap(); - var err = client.connect(req, '127.0.0.1', common.PORT); - assert.equal(err, 0); - - req.oncomplete = function(status, client_, req_) { - assert.equal(0, status); - assert.equal(client, client_); - assert.equal(req, req_); - - console.log('connected'); - var shutdownReq = new ShutdownWrap(); - var err = client.shutdown(shutdownReq); - assert.equal(err, 0); - - shutdownReq.oncomplete = function(status, client_, req_) { - console.log('shutdown complete'); - assert.equal(0, status); - assert.equal(client, client_); - assert.equal(shutdownReq, req_); - shutdownCount++; - client.close(); - }; - }; -} - -///// - -var connectCount = 0; -var endCount = 0; -var shutdownCount = 0; - -var server = require('net').Server(function(s) { - console.log('got connection'); - connectCount++; - s.resume(); - s.on('end', function() { - console.log('got eof'); - endCount++; - s.destroy(); - server.close(); - }); -}); - -server.listen(common.PORT, makeConnection); - -process.on('exit', function() { - assert.equal(1, shutdownCount); - assert.equal(1, connectCount); - assert.equal(1, endCount); -}); diff --git a/test/simple/test-tcp-wrap-listen.js b/test/simple/test-tcp-wrap-listen.js deleted file mode 100644 index 5801368ba..000000000 --- a/test/simple/test-tcp-wrap-listen.js +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var TCP = process.binding('tcp_wrap').TCP; -var WriteWrap = process.binding('stream_wrap').WriteWrap; - -var server = new TCP(); - -var r = server.bind('0.0.0.0', common.PORT); -assert.equal(0, r); - -server.listen(128); - -var slice, sliceCount = 0, eofCount = 0; - -var writeCount = 0; -var recvCount = 0; - -server.onconnection = function(err, client) { - assert.equal(0, client.writeQueueSize); - console.log('got connection'); - - function maybeCloseClient() { - if (client.pendingWrites.length == 0 && client.gotEOF) { - console.log('close client'); - client.close(); - } - } - - client.readStart(); - client.pendingWrites = []; - client.onread = function(err, buffer) { - if (buffer) { - assert.ok(buffer.length > 0); - - assert.equal(0, client.writeQueueSize); - - var req = new WriteWrap(); - req.async = false; - var err = client.writeBuffer(req, buffer); - assert.equal(err, 0); - client.pendingWrites.push(req); - - console.log('client.writeQueueSize: ' + client.writeQueueSize); - // 11 bytes should flush - assert.equal(0, client.writeQueueSize); - - if (req.async) - req.oncomplete = done; - else - process.nextTick(done.bind(null, 0, client, req)); - - function done(status, client_, req_) { - assert.equal(req, client.pendingWrites.shift()); - - // Check parameters. - assert.equal(0, status); - assert.equal(client, client_); - assert.equal(req, req_); - - console.log('client.writeQueueSize: ' + client.writeQueueSize); - assert.equal(0, client.writeQueueSize); - - writeCount++; - console.log('write ' + writeCount); - maybeCloseClient(); - }; - - sliceCount++; - } else { - console.log('eof'); - client.gotEOF = true; - server.close(); - eofCount++; - maybeCloseClient(); - } - }; -}; - -var net = require('net'); - -var c = net.createConnection(common.PORT); -c.on('connect', function() { - c.end('hello world'); -}); - -c.setEncoding('utf8'); -c.on('data', function(d) { - assert.equal('hello world', d); - recvCount++; -}); - -c.on('close', function() { - console.error('client closed'); -}); - -process.on('exit', function() { - assert.equal(1, sliceCount); - assert.equal(1, eofCount); - assert.equal(1, writeCount); - assert.equal(1, recvCount); -}); diff --git a/test/simple/test-tcp-wrap.js b/test/simple/test-tcp-wrap.js deleted file mode 100644 index bc1e14e68..000000000 --- a/test/simple/test-tcp-wrap.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var TCP = process.binding('tcp_wrap').TCP; -var uv = process.binding('uv'); - -var handle = new TCP(); - -// Should be able to bind to the common.PORT -var err = handle.bind('0.0.0.0', common.PORT); -assert.equal(err, 0); - -// Should not be able to bind to the same port again -err = handle.bind('0.0.0.0', common.PORT); -assert.equal(err, uv.UV_EINVAL); - -handle.close(); diff --git a/test/simple/test-timers-first-fire.js b/test/simple/test-timers-first-fire.js deleted file mode 100644 index e97b7ec85..000000000 --- a/test/simple/test-timers-first-fire.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var TIMEOUT = 50; -var last = process.hrtime(); -setTimeout(function() { - var hr = process.hrtime(last); - var ms = (hr[0] * 1e3) + (hr[1] / 1e6); - var delta = ms - TIMEOUT; - console.log('timer fired in', delta); - assert.ok(delta > 0, 'Timer fired early'); -}, TIMEOUT); diff --git a/test/simple/test-timers-immediate-queue.js b/test/simple/test-timers-immediate-queue.js deleted file mode 100644 index cce43a1ac..000000000 --- a/test/simple/test-timers-immediate-queue.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// setImmediate should run clear its queued cbs once per event loop turn -// but immediates queued while processing the current queue should happen -// on the next turn of the event loop. - -// in v0.10 hit should be 1, because we only process one cb per turn -// in v0.11 and beyond it should be the exact same size of QUEUE -// if we're letting things recursively add to the immediate QUEUE hit will be -// > QUEUE - -var ticked = false; - -var hit = 0; -var QUEUE = 1000; - -function run() { - if (hit === 0) - process.nextTick(function() { ticked = true; }); - - if (ticked) return; - - hit += 1; - setImmediate(run); -} - -for (var i = 0; i < QUEUE; i++) - setImmediate(run); - -process.on('exit', function() { - console.log('hit', hit); - assert.strictEqual(hit, QUEUE, 'We ticked between the immediate queue'); -}); diff --git a/test/simple/test-timers-immediate.js b/test/simple/test-timers-immediate.js deleted file mode 100644 index 0bd8ae964..000000000 --- a/test/simple/test-timers-immediate.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var immediateA = false, - immediateB = false, - immediateC = [], - before; - -setImmediate(function() { - try { - immediateA = process.hrtime(before); - } catch(e) { - console.log('failed to get hrtime with offset'); - } - clearImmediate(immediateB); -}); - -before = process.hrtime(); - -immediateB = setImmediate(function() { - immediateB = true; -}); - -setImmediate(function(x, y, z) { - immediateC = [x, y, z]; -}, 1, 2, 3); - -process.on('exit', function() { - assert.ok(immediateA, 'Immediate should happen after normal execution'); - assert.notStrictEqual(immediateB, true, 'immediateB should not fire'); - assert.deepEqual(immediateC, [1, 2, 3], 'immediateC args should match'); -}); diff --git a/test/simple/test-timers-linked-list.js b/test/simple/test-timers-linked-list.js deleted file mode 100644 index 0b6bf4bef..000000000 --- a/test/simple/test-timers-linked-list.js +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var L = require('_linklist'); - - -var list = { name: 'list' }; -var A = { name: 'A' }; -var B = { name: 'B' }; -var C = { name: 'C' }; -var D = { name: 'D' }; - - -L.init(list); -L.init(A); -L.init(B); -L.init(C); -L.init(D); - -assert.ok(L.isEmpty(list)); -assert.equal(null, L.peek(list)); - -L.append(list, A); -// list -> A -assert.equal(A, L.peek(list)); - -L.append(list, B); -// list -> A -> B -assert.equal(A, L.peek(list)); - -L.append(list, C); -// list -> A -> B -> C -assert.equal(A, L.peek(list)); - -L.append(list, D); -// list -> A -> B -> C -> D -assert.equal(A, L.peek(list)); - -var x = L.shift(list); -assert.equal(A, x); -// list -> B -> C -> D -assert.equal(B, L.peek(list)); - -x = L.shift(list); -assert.equal(B, x); -// list -> C -> D -assert.equal(C, L.peek(list)); - -// B is already removed, so removing it again shouldn't hurt. -L.remove(B); -// list -> C -> D -assert.equal(C, L.peek(list)); - -// Put B back on the list -L.append(list, B); -// list -> C -> D -> B -assert.equal(C, L.peek(list)); - -L.remove(C); -// list -> D -> B -assert.equal(D, L.peek(list)); - -L.remove(B); -// list -> D -assert.equal(D, L.peek(list)); - -L.remove(D); -// list -assert.equal(null, L.peek(list)); - - -assert.ok(L.isEmpty(list)); - - -L.append(list, D); -// list -> D -assert.equal(D, L.peek(list)); - -L.append(list, C); -L.append(list, B); -L.append(list, A); -// list -> D -> C -> B -> A - -// Append should REMOVE C from the list and append it to the end. -L.append(list, C); - -// list -> D -> B -> A -> C -assert.equal(D, L.shift(list)); -// list -> B -> A -> C -assert.equal(B, L.peek(list)); -assert.equal(B, L.shift(list)); -// list -> A -> C -assert.equal(A, L.peek(list)); -assert.equal(A, L.shift(list)); -// list -> C -assert.equal(C, L.peek(list)); -assert.equal(C, L.shift(list)); -// list -assert.ok(L.isEmpty(list)); - diff --git a/test/simple/test-timers-non-integer-delay.js b/test/simple/test-timers-non-integer-delay.js deleted file mode 100644 index db9bedafa..000000000 --- a/test/simple/test-timers-non-integer-delay.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * This test makes sure that non-integer timer delays do not make the process - * hang. See https://github.com/joyent/node/issues/8065 and - * https://github.com/joyent/node/issues/8068 which have been fixed by - * https://github.com/joyent/node/pull/8073. - * - * If the process hangs, this test will make the tests suite timeout, - * otherwise it will exit very quickly (after 50 timers with a short delay - * fire). - * - * We have to set at least several timers with a non-integer delay to - * reproduce the issue. Sometimes, a timer with a non-integer delay will - * expire correctly. 50 timers has always been more than enough to reproduce - * it 100%. - */ - -var assert = require('assert'); - -var TIMEOUT_DELAY = 1.1; -var NB_TIMEOUTS_FIRED = 50; - -var nbTimeoutFired = 0; -var interval = setInterval(function() { - ++nbTimeoutFired; - if (nbTimeoutFired === NB_TIMEOUTS_FIRED) { - clearInterval(interval); - process.exit(0); - } -}, TIMEOUT_DELAY); diff --git a/test/simple/test-timers-ordering.js b/test/simple/test-timers-ordering.js deleted file mode 100644 index 30cc44e53..000000000 --- a/test/simple/test-timers-ordering.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var Timer = process.binding('timer_wrap').Timer; - -var i; - -var N = 30; - -var last_i = 0; -var last_ts = 0; -var start = Timer.now(); - -var f = function(i) { - if (i <= N) { - // check order - assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + last_i + ' + 1'); - last_i = i; - - // check that this iteration is fired at least 1ms later than the previous - var now = Timer.now(); - console.log(i, now); - assert(now >= last_ts + 1, 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); - last_ts = now; - - // schedule next iteration - setTimeout(f, 1, i + 1); - } -}; -f(1); diff --git a/test/simple/test-timers-this.js b/test/simple/test-timers-this.js deleted file mode 100644 index 3d23e61df..000000000 --- a/test/simple/test-timers-this.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); - -var immediateThis, intervalThis, timeoutThis, - immediateArgsThis, intervalArgsThis, timeoutArgsThis; - -var immediateHandler = setImmediate(function () { - immediateThis = this; -}); - -var immediateArgsHandler = setImmediate(function () { - immediateArgsThis = this; -}, "args ..."); - -var intervalHandler = setInterval(function () { - clearInterval(intervalHandler); - - intervalThis = this; -}); - -var intervalArgsHandler = setInterval(function () { - clearInterval(intervalArgsHandler); - - intervalArgsThis = this; -}, 0, "args ..."); - -var timeoutHandler = setTimeout(function () { - timeoutThis = this; -}); - -var timeoutArgsHandler = setTimeout(function () { - timeoutArgsThis = this; -}, 0, "args ..."); - -process.once('exit', function () { - assert.strictEqual(immediateThis, immediateHandler); - assert.strictEqual(immediateArgsThis, immediateArgsHandler); - - assert.strictEqual(intervalThis, intervalHandler); - assert.strictEqual(intervalArgsThis, intervalArgsHandler); - - assert.strictEqual(timeoutThis, timeoutHandler); - assert.strictEqual(timeoutArgsThis, timeoutArgsHandler); -}); diff --git a/test/simple/test-timers-uncaught-exception.js b/test/simple/test-timers-uncaught-exception.js deleted file mode 100644 index 6e07fe084..000000000 --- a/test/simple/test-timers-uncaught-exception.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var exceptions = 0; -var timer1 = 0; -var timer2 = 0; - -// the first timer throws... -console.error('set first timer'); -setTimeout(function() { - console.error('first timer'); - timer1++; - throw new Error('BAM!'); -}, 100); - -// ...but the second one should still run -console.error('set second timer'); -setTimeout(function() { - console.error('second timer'); - assert.equal(timer1, 1); - timer2++; -}, 100); - -function uncaughtException(err) { - console.error('uncaught handler'); - assert.equal(err.message, 'BAM!'); - exceptions++; -} -process.on('uncaughtException', uncaughtException); - -var exited = false; -process.on('exit', function() { - assert(!exited); - exited = true; - process.removeListener('uncaughtException', uncaughtException); - assert.equal(exceptions, 1); - assert.equal(timer1, 1); - assert.equal(timer2, 1); -}); diff --git a/test/simple/test-timers-unref.js b/test/simple/test-timers-unref.js deleted file mode 100644 index 1c362cb83..000000000 --- a/test/simple/test-timers-unref.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var interval_fired = false, - timeout_fired = false, - unref_interval = false, - unref_timer = false, - interval, check_unref, checks = 0; - -var LONG_TIME = 10 * 1000; -var SHORT_TIME = 100; - -setInterval(function() { - interval_fired = true; -}, LONG_TIME).unref(); - -setTimeout(function() { - timeout_fired = true; -}, LONG_TIME).unref(); - -interval = setInterval(function() { - unref_interval = true; - clearInterval(interval); -}, SHORT_TIME).unref(); - -setTimeout(function() { - unref_timer = true; -}, SHORT_TIME).unref(); - -check_unref = setInterval(function() { - if (checks > 5 || (unref_interval && unref_timer)) - clearInterval(check_unref); - checks += 1; -}, 100); - -// Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. -(function() { - var t = setInterval(function() {}, 1); - process.nextTick(t.unref.bind({})); - process.nextTick(t.unref.bind(t)); -})(); - -process.on('exit', function() { - assert.strictEqual(interval_fired, false, 'Interval should not fire'); - assert.strictEqual(timeout_fired, false, 'Timeout should not fire'); - assert.strictEqual(unref_timer, true, 'An unrefd timeout should still fire'); - assert.strictEqual(unref_interval, true, 'An unrefd interval should still fire'); -}); diff --git a/test/simple/test-timers-zero-timeout.js b/test/simple/test-timers-zero-timeout.js deleted file mode 100644 index eb43f183f..000000000 --- a/test/simple/test-timers-zero-timeout.js +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// https://github.com/joyent/node/issues/2079 - zero timeout drops extra args -(function() { - var ncalled = 0; - - setTimeout(f, 0, 'foo', 'bar', 'baz'); - var timer = setTimeout(function() {}, 0); - - function f(a, b, c) { - assert.equal(a, 'foo'); - assert.equal(b, 'bar'); - assert.equal(c, 'baz'); - ncalled++; - } - - process.on('exit', function() { - assert.equal(ncalled, 1); - }); -})(); - -(function() { - var ncalled = 0; - - var iv = setInterval(f, 0, 'foo', 'bar', 'baz'); - - function f(a, b, c) { - assert.equal(a, 'foo'); - assert.equal(b, 'bar'); - assert.equal(c, 'baz'); - if (++ncalled == 3) clearTimeout(iv); - } - - process.on('exit', function() { - assert.equal(ncalled, 3); - }); -})(); diff --git a/test/simple/test-timers.js b/test/simple/test-timers.js deleted file mode 100644 index 98e6bc3de..000000000 --- a/test/simple/test-timers.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var inputs = [ - undefined, - null, - true, - false, - '', - [], - {}, - NaN, - +Infinity, - -Infinity, - (1.0 / 0.0), // sanity check - parseFloat('x'), // NaN - -10, - -1, - -0.5, - -0.0, - 0, - 0.0, - 0.5, - 1, - 1.0, - 10, - 2147483648, // browser behaviour: timeouts > 2^31-1 run on next tick - 12345678901234 // ditto -]; - -var timeouts = []; -var intervals = []; - -inputs.forEach(function(value, index) { - setTimeout(function() { - timeouts[index] = true; - }, value); - - var handle = setInterval(function() { - clearInterval(handle); // disarm timer or we'll never finish - intervals[index] = true; - }, value); -}); - -process.on('exit', function() { - // assert that all timers have run - inputs.forEach(function(value, index) { - assert.equal(true, timeouts[index]); - assert.equal(true, intervals[index]); - }); -}); diff --git a/test/simple/test-tls-0-dns-altname.js b/test/simple/test-tls-0-dns-altname.js deleted file mode 100644 index 002a5ca3c..000000000 --- a/test/simple/test-tls-0-dns-altname.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var net = require('net'); -var tls = require('tls'); - -var common = require('../common'); - -var requests = 0; - -var server = tls.createServer({ - key: fs.readFileSync(common.fixturesDir + '/keys/0-dns-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/0-dns-cert.pem') -}, function(c) { - c.once('data', function() { - c.destroy(); - server.close(); - }); -}).listen(common.PORT, function() { - var c = tls.connect(common.PORT, { - rejectUnauthorized: false - }, function() { - requests++; - var cert = c.getPeerCertificate(); - assert.equal(cert.subjectaltname, - 'DNS:google.com\0.evil.com, ' + - 'DNS:just-another.com, ' + - 'IP Address:8.8.8.8, '+ - 'IP Address:8.8.4.4, '+ - 'DNS:last.com'); - c.write('ok'); - }); -}); - -process.on('exit', function() { - assert.equal(requests, 1); -}); diff --git a/test/simple/test-tls-alert.js b/test/simple/test-tls-alert.js deleted file mode 100644 index f26b496f9..000000000 --- a/test/simple/test-tls-alert.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); -var spawn = require('child_process').spawn; - -var success = false; - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} - -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} - -var server = tls.Server({ - secureProtocol: 'TLSv1_2_server_method', - key: loadPEM('agent2-key'), - cert:loadPEM('agent2-cert') -}, null).listen(common.PORT, function() { - var args = ['s_client', '-quiet', '-tls1_1','-connect', '127.0.0.1:' + common.PORT]; - var client = spawn(common.opensslCli, args); - var out = ''; - client.stderr.setEncoding('utf8'); - client.stderr.on('data', function(d) { - out += d; - if (/SSL alert number 70/.test(out)) { - success = true; - server.close(); - } - }); -}); -process.on('exit', function() { - assert(success); -}); diff --git a/test/simple/test-tls-cert-regression.js b/test/simple/test-tls-cert-regression.js deleted file mode 100644 index ec8369ba9..000000000 --- a/test/simple/test-tls-cert-regression.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var tls = require('tls'); - -var assert = require('assert'); -var common = require('../common'); - -var cert = '-----BEGIN CERTIFICATE-----\n' + - 'MIIBfjCCASgCCQDmmNjAojbDQjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\n' + - 'VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\n' + - 'cyBQdHkgTHRkMCAXDTE0MDExNjE3NTMxM1oYDzIyODcxMDMxMTc1MzEzWjBFMQsw\n' + - 'CQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJu\n' + - 'ZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPKwlfMX\n' + - '6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+wsU1O9FzRIVmpeIjDXhbp\n' + - 'Mjsa1HtzSiccPXsCAwEAATANBgkqhkiG9w0BAQUFAANBAHOoKy0NkyfiYH7Ne5ka\n' + - 'uvCyndyeB4d24FlfqEUlkfaWCZlNKRaV9YhLDiEg3BcIreFo4brtKQfZzTRs0GVm\n' + - 'KHg=\n' + - '-----END CERTIFICATE-----'; -var key = '-----BEGIN RSA PRIVATE KEY-----\n' + - 'MIIBPQIBAAJBAPKwlfMX6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+w\n' + - 'sU1O9FzRIVmpeIjDXhbpMjsa1HtzSiccPXsCAwEAAQJBAM4uU9aJE0OfdE1p/X+K\n' + - 'LrCT3XMdFCJ24GgmHyOURtwDy18upQJecDVdcZp16fjtOPmaW95GoYRyifB3R4I5\n' + - 'RxECIQD7jRM9slCSVV8xp9kOJQNpHjhRQYVGBn+pyllS2sb+RQIhAPb7Y+BIccri\n' + - 'NWnuhwCW8hA7Fkj/kaBdAwyW7L3Tvui/AiEAiqLCovMecre4Yi6GcsQ1b/6mvSmm\n' + - 'IOS+AT6zIfXPTB0CIQCJKGR3ymN/Qw5crL1GQ41cHCQtF9ickOq/lBUW+j976wIh\n' + - 'AOaJnkQrmurlRdePX6LvN/LgGAQoxwovfjcOYNnZsIVY\n' + - '-----END RSA PRIVATE KEY-----'; - -function test(cert, key, cb) { - var server = tls.createServer({ - cert: cert, - key: key - }).listen(common.PORT, function() { - server.close(cb); - }); -} - -var completed = false; -test(cert, key, function() { - test(new Buffer(cert), new Buffer(key), function() { - completed = true; - }); -}); - -process.on('exit', function() { - assert(completed); -}); diff --git a/test/simple/test-tls-check-server-identity.js b/test/simple/test-tls-check-server-identity.js deleted file mode 100644 index 598dac0e0..000000000 --- a/test/simple/test-tls-check-server-identity.js +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var tls = require('tls'); - -var tests = [ - // Basic CN handling - { host: 'a.com', cert: { subject: { CN: 'a.com' } } }, - { host: 'a.com', cert: { subject: { CN: 'A.COM' } } }, - { - host: 'a.com', - cert: { subject: { CN: 'b.com' } }, - error: 'Host: a.com. is not cert\'s CN: b.com' - }, - { host: 'a.com', cert: { subject: { CN: 'a.com.' } } }, - - // Wildcards in CN - { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } } }, - { host: 'b.a.com', cert: { - subjectaltname: 'DNS:omg.com', - subject: { CN: '*.a.com' } }, - error: 'Host: b.a.com. is not in the cert\'s altnames: ' + - 'DNS:omg.com' - }, - - // Multiple CN fields - { - host: 'foo.com', cert: { - subject: { CN: ['foo.com', 'bar.com'] } // CN=foo.com; CN=bar.com; - } - }, - - // DNS names and CN - { - host: 'a.com', cert: { - subjectaltname: 'DNS:*', - subject: { CN: 'b.com' } - }, - error: 'Host: a.com. is not in the cert\'s altnames: ' + - 'DNS:*' - }, - { - host: 'a.com', cert: { - subjectaltname: 'DNS:*.com', - subject: { CN: 'b.com' } - }, - error: 'Host: a.com. is not in the cert\'s altnames: ' + - 'DNS:*.com' - }, - { - host: 'a.co.uk', cert: { - subjectaltname: 'DNS:*.co.uk', - subject: { CN: 'b.com' } - } - }, - { - host: 'a.com', cert: { - subjectaltname: 'DNS:*.a.com', - subject: { CN: 'a.com' } - }, - error: 'Host: a.com. is not in the cert\'s altnames: ' + - 'DNS:*.a.com' - }, - { - host: 'a.com', cert: { - subjectaltname: 'DNS:*.a.com', - subject: { CN: 'b.com' } - }, - error: 'Host: a.com. is not in the cert\'s altnames: ' + - 'DNS:*.a.com' - }, - { - host: 'a.com', cert: { - subjectaltname: 'DNS:a.com', - subject: { CN: 'b.com' } - } - }, - { - host: 'a.com', cert: { - subjectaltname: 'DNS:A.COM', - subject: { CN: 'b.com' } - } - }, - - // DNS names - { - host: 'a.com', cert: { - subjectaltname: 'DNS:*.a.com', - subject: {} - }, - error: 'Host: a.com. is not in the cert\'s altnames: ' + - 'DNS:*.a.com' - }, - { - host: 'b.a.com', cert: { - subjectaltname: 'DNS:*.a.com', - subject: {} - } - }, - { - host: 'c.b.a.com', cert: { - subjectaltname: 'DNS:*.a.com', - subject: {} - }, - error: 'Host: c.b.a.com. is not in the cert\'s altnames: ' + - 'DNS:*.a.com' - }, - { - host: 'b.a.com', cert: { - subjectaltname: 'DNS:*b.a.com', - subject: {} - } - }, - { - host: 'a-cb.a.com', cert: { - subjectaltname: 'DNS:*b.a.com', - subject: {} - } - }, - { - host: 'a.b.a.com', cert: { - subjectaltname: 'DNS:*b.a.com', - subject: {} - }, - error: 'Host: a.b.a.com. is not in the cert\'s altnames: ' + - 'DNS:*b.a.com' - }, - // Mutliple DNS names - { - host: 'a.b.a.com', cert: { - subjectaltname: 'DNS:*b.a.com, DNS:a.b.a.com', - subject: {} - } - }, - // URI names - { - host: 'a.b.a.com', cert: { - subjectaltname: 'URI:http://a.b.a.com/', - subject: {} - } - }, - { - host: 'a.b.a.com', cert: { - subjectaltname: 'URI:http://*.b.a.com/', - subject: {} - }, - error: 'Host: a.b.a.com. is not in the cert\'s altnames: ' + - 'URI:http://*.b.a.com/' - }, - // IP addresses - { - host: 'a.b.a.com', cert: { - subjectaltname: 'IP Address:127.0.0.1', - subject: {} - }, - error: 'Host: a.b.a.com. is not in the cert\'s altnames: ' + - 'IP Address:127.0.0.1' - }, - { - host: '127.0.0.1', cert: { - subjectaltname: 'IP Address:127.0.0.1', - subject: {} - } - }, - { - host: '127.0.0.2', cert: { - subjectaltname: 'IP Address:127.0.0.1', - subject: {} - }, - error: 'IP: 127.0.0.2 is not in the cert\'s list: ' + - '127.0.0.1' - }, - { - host: '127.0.0.1', cert: { - subjectaltname: 'DNS:a.com', - subject: {} - }, - error: 'IP: 127.0.0.1 is not in the cert\'s list: ' - }, - { - host: 'localhost', cert: { - subjectaltname: 'DNS:a.com', - subject: { CN: 'localhost' } - }, - error: 'Host: localhost. is not in the cert\'s altnames: ' + - 'DNS:a.com' - }, -]; - -tests.forEach(function(test, i) { - var err = tls.checkServerIdentity(test.host, test.cert); - assert.equal(err && err.reason, - test.error, - 'Test#' + i + ' failed: ' + util.inspect(test) + '\n' + - test.error + ' != ' + (err && err.reason)); -}); diff --git a/test/simple/test-tls-client-abort.js b/test/simple/test-tls-client-abort.js deleted file mode 100644 index 8958ceb15..000000000 --- a/test/simple/test-tls-client-abort.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); -var path = require('path'); - -var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); -var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - -var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { - assert.ok(false); // callback should never be executed -}); -conn.on('error', function() { -}); -assert.doesNotThrow(function() { - conn.destroy(); -}); - diff --git a/test/simple/test-tls-client-abort2.js b/test/simple/test-tls-client-abort2.js deleted file mode 100644 index f81196276..000000000 --- a/test/simple/test-tls-client-abort2.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); - -var errors = 0; - -var conn = tls.connect(common.PORT, function() { - assert(false); // callback should never be executed -}); -conn.on('error', function() { - ++errors; - assert.doesNotThrow(function() { - conn.destroy(); - }); -}); - -process.on('exit', function() { - assert.equal(errors, 1); -}); diff --git a/test/simple/test-tls-client-default-ciphers.js b/test/simple/test-tls-client-default-ciphers.js deleted file mode 100644 index 0a3c47029..000000000 --- a/test/simple/test-tls-client-default-ciphers.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var common = require('../common'); -var tls = require('tls'); - -function test1() { - var ciphers = ''; - tls.createSecureContext = function(options) { - ciphers = options.ciphers - } - var s = tls.connect(common.PORT); - s.destroy(); - assert.equal(ciphers, tls.DEFAULT_CIPHERS); -} -test1(); diff --git a/test/simple/test-tls-client-destroy-soon.js b/test/simple/test-tls-client-destroy-soon.js deleted file mode 100644 index 529b84a73..000000000 --- a/test/simple/test-tls-client-destroy-soon.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Create an ssl server. First connection, validate that not resume. -// Cache session and close connection. Use session on second connection. -// ASSERT resumption. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') -}; - -var big = new Buffer(2 * 1024 * 1024); -var connections = 0; -var bytesRead = 0; - -big.fill('Y'); - -// create server -var server = tls.createServer(options, function(socket) { - socket.end(big); - socket.destroySoon(); - connections++; -}); - -// start listening -server.listen(common.PORT, function() { - var client = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - client.on('readable', function() { - var d = client.read(); - if (d) - bytesRead += d.length; - }); - - client.on('end', function() { - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(1, connections); - assert.equal(big.length, bytesRead); -}); diff --git a/test/simple/test-tls-client-reject.js b/test/simple/test-tls-client-reject.js deleted file mode 100644 index bae961498..000000000 --- a/test/simple/test-tls-client-reject.js +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var path = require('path'); - -var options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) -}; - -var connectCount = 0; - -var server = tls.createServer(options, function(socket) { - ++connectCount; - socket.on('data', function(data) { - common.debug(data.toString()); - assert.equal(data, 'ok'); - }); -}).listen(common.PORT, function() { - unauthorized(); -}); - -function unauthorized() { - var socket = tls.connect({ - port: common.PORT, - servername: 'localhost', - rejectUnauthorized: false - }, function() { - assert(!socket.authorized); - socket.end(); - rejectUnauthorized(); - }); - socket.on('error', function(err) { - assert(false); - }); - socket.write('ok'); -} - -function rejectUnauthorized() { - var socket = tls.connect(common.PORT, { - servername: 'localhost' - }, function() { - assert(false); - }); - socket.on('error', function(err) { - common.debug(err); - authorized(); - }); - socket.write('ng'); -} - -function authorized() { - var socket = tls.connect(common.PORT, { - ca: [fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))], - servername: 'localhost' - }, function() { - assert(socket.authorized); - socket.end(); - server.close(); - }); - socket.on('error', function(err) { - assert(false); - }); - socket.write('ok'); -} - -process.on('exit', function() { - assert.equal(connectCount, 3); -}); diff --git a/test/simple/test-tls-client-resume.js b/test/simple/test-tls-client-resume.js deleted file mode 100644 index 7271134df..000000000 --- a/test/simple/test-tls-client-resume.js +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Create an ssl server. First connection, validate that not resume. -// Cache session and close connection. Use session on second connection. -// ASSERT resumption. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') -}; - -var connections = 0; - -// create server -var server = tls.Server(options, function(socket) { - socket.end('Goodbye'); - connections++; -}); - -// start listening -server.listen(common.PORT, function() { - - var session1 = null; - var client1 = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - console.log('connect1'); - assert.ok(!client1.isSessionReused(), 'Session *should not* be reused.'); - session1 = client1.getSession(); - }); - - client1.on('close', function() { - console.log('close1'); - - var opts = { - port: common.PORT, - rejectUnauthorized: false, - session: session1 - }; - - var client2 = tls.connect(opts, function() { - console.log('connect2'); - assert.ok(client2.isSessionReused(), 'Session *should* be reused.'); - }); - - client2.on('close', function() { - console.log('close2'); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(2, connections); -}); diff --git a/test/simple/test-tls-client-verify.js b/test/simple/test-tls-client-verify.js deleted file mode 100644 index 590dfc6e6..000000000 --- a/test/simple/test-tls-client-verify.js +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - - -var hosterr = /Hostname\/IP doesn\'t match certificate\'s altnames/g; -var testCases = - [{ ca: ['ca1-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: 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: ['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' } - ] - } - ]; - - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); - - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} - - -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} - -var successfulTests = 0; - -function testServers(index, servers, clientOptions, cb) { - var serverOptions = servers[index]; - if (!serverOptions) { - cb(); - return; - } - - var ok = serverOptions.ok; - - if (serverOptions.key) { - serverOptions.key = loadPEM(serverOptions.key); - } - - if (serverOptions.cert) { - serverOptions.cert = loadPEM(serverOptions.cert); - } - - var server = tls.createServer(serverOptions, function(s) { - s.end('hello world\n'); - }); - - server.listen(common.PORT, function() { - var b = ''; - - console.error('connecting...'); - var client = tls.connect(clientOptions, function() { - var authorized = client.authorized || - hosterr.test(client.authorizationError); - - console.error('expected: ' + ok + ' authed: ' + authorized); - - assert.equal(ok, authorized); - server.close(); - }); - - client.on('data', function(d) { - b += d.toString(); - }); - - client.on('end', function() { - assert.equal('hello world\n', b); - }); - - client.on('close', function() { - testServers(index + 1, servers, clientOptions, cb); - }); - }); -} - - -function runTest(testIndex) { - var tcase = testCases[testIndex]; - if (!tcase) return; - - var clientOptions = { - port: common.PORT, - ca: tcase.ca.map(loadPEM), - key: loadPEM(tcase.key), - cert: loadPEM(tcase.cert), - rejectUnauthorized: false - }; - - - testServers(0, tcase.servers, clientOptions, function() { - successfulTests++; - runTest(testIndex + 1); - }); -} - - -runTest(0); - - -process.on('exit', function() { - console.log('successful tests: %d', successfulTests); - assert.equal(successfulTests, testCases.length); -}); diff --git a/test/simple/test-tls-close-notify.js b/test/simple/test-tls-close-notify.js deleted file mode 100644 index 3c6bf53f2..000000000 --- a/test/simple/test-tls-close-notify.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var net = require('net'); -var tls = require('tls'); - -var common = require('../common'); - -var ended = 0; - -var server = tls.createServer({ - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}, function(c) { - // Send close-notify without shutting down TCP socket - if (c.ssl.shutdown() !== 1) - c.ssl.shutdown(); -}).listen(common.PORT, function() { - var c = tls.connect(common.PORT, { - rejectUnauthorized: false - }, function() { - // Ensure that we receive 'end' event anyway - c.on('end', function() { - ended++; - c.destroy(); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(ended, 1); -}); diff --git a/test/simple/test-tls-connect-given-socket.js b/test/simple/test-tls-connect-given-socket.js deleted file mode 100644 index ab571c7a8..000000000 --- a/test/simple/test-tls-connect-given-socket.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var net = require('net'); -var fs = require('fs'); -var path = require('path'); - -var serverConnected = 0; -var clientConnected = 0; - -var options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) -}; - -var server = tls.createServer(options, function(socket) { - serverConnected++; - socket.end('Hello'); -}).listen(common.PORT, function() { - var waiting = 2; - function establish(socket) { - var client = tls.connect({ - rejectUnauthorized: false, - socket: socket - }, function() { - clientConnected++; - var data = ''; - client.on('data', function(chunk) { - data += chunk.toString(); - }); - client.on('end', function() { - assert.equal(data, 'Hello'); - if (--waiting === 0) - server.close(); - }); - }); - assert(client.readable); - assert(client.writable); - } - - // Already connected socket - var connected = net.connect(common.PORT, function() { - establish(connected); - }); - - // Connecting socket - var connecting = net.connect(common.PORT); - establish(connecting); -}); - -process.on('exit', function() { - assert.equal(serverConnected, 2); - assert.equal(clientConnected, 2); -}); diff --git a/test/simple/test-tls-connect-pipe.js b/test/simple/test-tls-connect-pipe.js deleted file mode 100644 index 98031c0ad..000000000 --- a/test/simple/test-tls-connect-pipe.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var clientConnected = 0; -var serverConnected = 0; - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = tls.Server(options, function(socket) { - ++serverConnected; - server.close(); -}); -server.listen(common.PIPE, function() { - var options = { rejectUnauthorized: false }; - var client = tls.connect(common.PIPE, options, function() { - ++clientConnected; - client.end(); - }); -}); - -process.on('exit', function() { - assert.equal(clientConnected, 1); - assert.equal(serverConnected, 1); -}); diff --git a/test/simple/test-tls-connect-simple.js b/test/simple/test-tls-connect-simple.js deleted file mode 100644 index e896dd9e2..000000000 --- a/test/simple/test-tls-connect-simple.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var clientConnected = 0; -var serverConnected = 0; - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = tls.Server(options, function(socket) { - if (++serverConnected === 2) { - server.close(); - } -}); - -server.listen(common.PORT, function() { - var client1 = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - ++clientConnected; - client1.end(); - }); - - var client2 = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }); - client2.on('secureConnect', function() { - ++clientConnected; - client2.end(); - }); -}); - -process.on('exit', function() { - assert.equal(clientConnected, 2); - assert.equal(serverConnected, 2); -}); diff --git a/test/simple/test-tls-connect.js b/test/simple/test-tls-connect.js deleted file mode 100644 index 616f76c05..000000000 --- a/test/simple/test-tls-connect.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); -var path = require('path'); - -// https://github.com/joyent/node/issues/1218 -// uncatchable exception on TLS connection error -(function() { - var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); - var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - - var errorEmitted = false; - - process.on('exit', function() { - assert.ok(errorEmitted); - }); - - var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { - assert.ok(false); // callback should never be executed - }); - - conn.on('error', function() { - errorEmitted = true; - }); -})(); - -// SSL_accept/SSL_connect error handling -(function() { - var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); - var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - - var errorEmitted = false; - - process.on('exit', function() { - assert.ok(errorEmitted); - }); - - var conn = tls.connect({ - cert: cert, - key: key, - port: common.PORT, - ciphers: 'rick-128-roll' - }, function() { - assert.ok(false); // callback should never be executed - }); - - conn.on('error', function() { - errorEmitted = true; - }); -})(); diff --git a/test/simple/test-tls-delayed-attach.js b/test/simple/test-tls-delayed-attach.js deleted file mode 100644 index ceacedc73..000000000 --- a/test/simple/test-tls-delayed-attach.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var net = require('net'); -var tls = require('tls'); - -var common = require('../common'); - -var sent = 'hello world'; -var received = ''; -var ended = 0; - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = net.createServer(function(c) { - setTimeout(function() { - var s = new tls.TLSSocket(c, { - isServer: true, - secureContext: tls.createSecureContext(options) - }); - - s.on('data', function(chunk) { - received += chunk; - }); - - s.on('end', function() { - ended++; - server.close(); - s.destroy(); - }); - }, 200); -}).listen(common.PORT, function() { - var c = tls.connect(common.PORT, { - rejectUnauthorized: false - }, function() { - c.end(sent); - }); -}); - -process.on('exit', function() { - assert.equal(received, sent); - assert.equal(ended, 1); -}); diff --git a/test/simple/test-tls-dhe.js b/test/simple/test-tls-dhe.js deleted file mode 100644 index 3975c5ed4..000000000 --- a/test/simple/test-tls-dhe.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var spawn = require('child_process').spawn; -var tls = require('tls'); -var fs = require('fs'); -var key = fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'); -var nsuccess = 0; -var ntests = 0; -var ciphers = 'DHE-RSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256'; - - -function loadDHParam(n) { - var path = common.fixturesDir; - if (n !== 'error') path += '/keys'; - return fs.readFileSync(path + '/dh' + n + '.pem'); -} - -function test(keylen, expectedCipher, cb) { - var options = { - key: key, - cert: cert, - dhparam: loadDHParam(keylen) - }; - - var server = tls.createServer(options, function(conn) { - conn.end(); - }); - - server.on('close', function(err) { - assert(!err); - if (cb) cb(); - }); - - server.listen(common.PORT, '127.0.0.1', function() { - var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT, - '-cipher', ciphers]; - var client = spawn(common.opensslCli, args); - var out = ''; - client.stdout.setEncoding('utf8'); - client.stdout.on('data', function(d) { - out += d; - }); - client.stdout.on('end', function() { - // DHE key length can be checked -brief option in s_client but it - // is only supported in openssl 1.0.2 so we cannot check it. - var reg = new RegExp('Cipher : ' + expectedCipher); - if (reg.test(out)) { - nsuccess++; - server.close(); - } - }); - }); -} - -function test512() { - test(512, 'DHE-RSA-AES128-SHA256', test1024); - ntests++; -} - -function test1024() { - test(1024, 'DHE-RSA-AES128-SHA256', test2048); - ntests++; -} - -function test2048() { - test(2048, 'DHE-RSA-AES128-SHA256', testError); - ntests++; -} - -function testError() { - test('error', 'ECDHE-RSA-AES128-SHA256', null); - ntests++; -} - -test512(); - -process.on('exit', function() { - assert.equal(ntests, nsuccess); -}); diff --git a/test/simple/test-tls-ecdh-disable.js b/test/simple/test-tls-ecdh-disable.js deleted file mode 100644 index 06b4e4ffd..000000000 --- a/test/simple/test-tls-ecdh-disable.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var exec = require('child_process').exec; -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), - ciphers: 'ECDHE-RSA-RC4-SHA', - ecdhCurve: false -}; - -var nconns = 0; - -process.on('exit', function() { - assert.equal(nconns, 0); -}); - -var server = tls.createServer(options, function(conn) { - conn.end(); - nconns++; -}); - -server.listen(common.PORT, '127.0.0.1', function() { - var cmd = common.opensslCli + ' s_client -cipher ' + options.ciphers + - ' -connect 127.0.0.1:' + common.PORT; - - exec(cmd, function(err, stdout, stderr) { - // Old versions of openssl will still exit with 0 so we - // can't just check if err is not null. - assert.notEqual(stderr.indexOf('handshake failure'), -1); - server.close(); - }); -}); diff --git a/test/simple/test-tls-ecdh.js b/test/simple/test-tls-ecdh.js deleted file mode 100644 index 446d76c83..000000000 --- a/test/simple/test-tls-ecdh.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var exec = require('child_process').exec; -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), - ciphers: '-ALL:ECDHE-RSA-RC4-SHA', - ecdhCurve: 'prime256v1' -}; - -var reply = 'I AM THE WALRUS'; // something recognizable -var nconns = 0; -var response = ''; - -process.on('exit', function() { - assert.equal(nconns, 1); - assert.notEqual(response.indexOf(reply), -1); -}); - -var server = tls.createServer(options, function(conn) { - conn.end(reply); - nconns++; -}); - -server.listen(common.PORT, '127.0.0.1', function() { - var cmd = common.opensslCli + ' s_client -cipher ' + options.ciphers + - ' -connect 127.0.0.1:' + common.PORT; - - exec(cmd, function(err, stdout, stderr) { - if (err) throw err; - response = stdout; - server.close(); - }); -}); diff --git a/test/simple/test-tls-econnreset.js b/test/simple/test-tls-econnreset.js deleted file mode 100644 index fcadf13f0..000000000 --- a/test/simple/test-tls-econnreset.js +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); - -var cacert = '-----BEGIN CERTIFICATE-----\n' + - 'MIIBxTCCAX8CAnXnMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n' + - 'VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\n' + - 'TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\n' + - 'bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMH0xCzAJ\n' + - 'BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZ\n' + - 'MBcGA1UEChMQU3Ryb25nTG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow\n' + - 'GAYDVQQDExFjYS5zdHJvbmdsb29wLmNvbTBMMA0GCSqGSIb3DQEBAQUAAzsAMDgC\n' + - 'MQDKbQ6rIR5t1q1v4Ha36jrq0IkyUohy9EYNvLnXUly1PGqxby0ILlAVJ8JawpY9\n' + - 'AVkCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\n' + - '+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\n' + - '-----END CERTIFICATE-----\n'; - -var cert = '-----BEGIN CERTIFICATE-----\n' + - 'MIIBfDCCATYCAgQaMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n' + - 'VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\n' + - 'TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\n' + - 'bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMBkxFzAV\n' + - 'BgNVBAMTDnN0cm9uZ2xvb3AuY29tMEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\n' + - 'I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01WpfGUaJr1a41K8Uq7xwID\n' + - 'AQABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA\n' + - 'cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU\n' + - '-----END CERTIFICATE-----\n'; - -var key = '-----BEGIN RSA PRIVATE KEY-----\n' + - 'MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo\n' + - 'mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg\n' + - '/JWMU/6hS36TsYyZMxwswQIZAPTAfht/zDLb7Hwgu2twsS1Ra9w/yyvtlwIZANET\n' + - '26votwJAHK1yUrZGA5nnp5qcmQ/JUQIZAII5YV/UUZvF9D/fUplJ7puENPWNY9bN\n' + - 'pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\n' + - 'YqrWTeQFNQ==\n' + - '-----END RSA PRIVATE KEY-----\n'; - -var ca = [ cert, cacert ]; - -var clientError = null; -var connectError = null; - -var server = tls.createServer({ ca: ca, cert: cert, key: key }, function(conn) { - throw 'unreachable'; -}).on('clientError', function(err, conn) { - assert(!clientError && conn); - clientError = err; -}).listen(common.PORT, function() { - var options = { - ciphers: 'AES128-GCM-SHA256', - port: common.PORT, - ca: ca - }; - tls.connect(options).on('error', function(err) { - assert(!connectError); - - connectError = err; - this.destroy(); - server.close(); - }).write('123'); -}); - -process.on('exit', function() { - assert(clientError); - assert(connectError); - assert(/socket hang up/.test(clientError.message)); - assert(/ECONNRESET/.test(clientError.code)); -}); diff --git a/test/simple/test-tls-fast-writing.js b/test/simple/test-tls-fast-writing.js deleted file mode 100644 index 894ec346a..000000000 --- a/test/simple/test-tls-fast-writing.js +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var tls = require('tls'); -var fs = require('fs'); - -var PORT = common.PORT; -var dir = common.fixturesDir; -var options = { key: fs.readFileSync(dir + '/test_key.pem'), - cert: fs.readFileSync(dir + '/test_cert.pem'), - ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; - -var server = tls.createServer(options, onconnection); -var gotChunk = false; -var gotDrain = false; - -var timer = setTimeout(function() { - console.log('not ok - timed out'); - process.exit(1); -}, 500); - -function onconnection(conn) { - conn.on('data', function(c) { - if (!gotChunk) { - gotChunk = true; - console.log('ok - got chunk'); - } - - // just some basic sanity checks. - assert(c.length); - assert(Buffer.isBuffer(c)); - - if (gotDrain) - process.exit(0); - }); -} - -server.listen(PORT, function() { - var chunk = new Buffer(1024); - chunk.fill('x'); - var opt = { port: PORT, rejectUnauthorized: false }; - var conn = tls.connect(opt, function() { - conn.on('drain', ondrain); - write(); - }); - function ondrain() { - if (!gotDrain) { - gotDrain = true; - console.log('ok - got drain'); - } - if (gotChunk) - process.exit(0); - write(); - } - function write() { - // this needs to return false eventually - while (false !== conn.write(chunk)); - } -}); diff --git a/test/simple/test-tls-friendly-error-message.js b/test/simple/test-tls-friendly-error-message.js deleted file mode 100644 index 39fb30231..000000000 --- a/test/simple/test-tls-friendly-error-message.js +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); - -var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); - -tls.createServer({ key: key, cert: cert }, function(conn) { - conn.end(); - this.close(); -}).listen(0, function() { - var options = { port: this.address().port, rejectUnauthorized: true }; - tls.connect(options).on('error', common.mustCall(function(err) { - assert.equal(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); - assert.equal(err.message, 'unable to verify the first certificate'); - this.destroy(); - })); -}); diff --git a/test/simple/test-tls-getcipher.js b/test/simple/test-tls-getcipher.js deleted file mode 100644 index 22a280e58..000000000 --- a/test/simple/test-tls-getcipher.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var cipher_list = ['RC4-SHA', 'AES256-SHA']; -var cipher_version_pattern = /TLS|SSL/; -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), - ciphers: cipher_list.join(':'), - honorCipherOrder: true -}; - -var nconns = 0; - -process.on('exit', function() { - assert.equal(nconns, 1); -}); - -var server = tls.createServer(options, function(cleartextStream) { - nconns++; -}); - -server.listen(common.PORT, '127.0.0.1', function() { - var client = tls.connect({ - host: '127.0.0.1', - port: common.PORT, - rejectUnauthorized: false - }, function() { - var cipher = client.getCipher(); - assert.equal(cipher.name, cipher_list[0]); - assert(cipher_version_pattern.test(cipher.version)); - client.end(); - server.close(); - }); -}); diff --git a/test/simple/test-tls-handshake-nohang.js b/test/simple/test-tls-handshake-nohang.js deleted file mode 100644 index de36ebb50..000000000 --- a/test/simple/test-tls-handshake-nohang.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); - -// neither should hang -tls.createSecurePair(null, false, false, false); -tls.createSecurePair(null, true, false, false); diff --git a/test/simple/test-tls-hello-parser-failure.js b/test/simple/test-tls-hello-parser-failure.js deleted file mode 100644 index b6c0ac228..000000000 --- a/test/simple/test-tls-hello-parser-failure.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var tls = require('tls'); -var net = require('net'); -var fs = require('fs'); -var assert = require('assert'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/test_key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem') -}; - -var bonkers = new Buffer(1024 * 1024); -bonkers.fill(42); - -var server = tls.createServer(options, function(c) { - -}).listen(common.PORT, function() { - var client = net.connect(common.PORT, function() { - client.write(bonkers); - }); - - var once = false; - - var writeAgain = setTimeout(function() { - client.write(bonkers); - }); - - client.on('error', function(err) { - if (!once) { - clearTimeout(writeAgain); - once = true; - client.destroy(); - server.close(); - } - }); - - client.on('close', function (hadError) { - assert.strictEqual(hadError, true, 'Client never errored'); - }); -}); diff --git a/test/simple/test-tls-honorcipherorder.js b/test/simple/test-tls-honorcipherorder.js deleted file mode 100644 index 6b24d7514..000000000 --- a/test/simple/test-tls-honorcipherorder.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var nconns = 0; -// test only in TLSv1 to use DES which is no longer supported TLSv1.2 -// to be safe when the default method is updated in the future -var SSL_Method = 'TLSv1_method'; -var localhost = '127.0.0.1'; - -process.on('exit', function() { - assert.equal(nconns, 6); -}); - -function test(honorCipherOrder, clientCipher, expectedCipher, cb) { - var soptions = { - secureProtocol: SSL_Method, - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), - ciphers: 'DES-CBC-SHA:AES256-SHA:RC4-SHA:ECDHE-RSA-AES256-SHA', - honorCipherOrder: !!honorCipherOrder - }; - - var server = tls.createServer(soptions, function(cleartextStream) { - nconns++; - - // End socket to send CLOSE_NOTIFY and TCP FIN packet, otherwise - // it may hang for ~30 seconds in FIN_WAIT_1 state (at least on OSX). - cleartextStream.end(); - }); - server.listen(common.PORT, localhost, function() { - var coptions = { - rejectUnauthorized: false, - secureProtocol: SSL_Method - }; - if (clientCipher) { - coptions.ciphers = clientCipher; - } - var client = tls.connect(common.PORT, localhost, coptions, function() { - var cipher = client.getCipher(); - client.end(); - server.close(); - assert.equal(cipher.name, expectedCipher); - if (cb) cb(); - }); - }); -} - -test1(); - -function test1() { - // Client has the preference of cipher suites by default - test(false, 'AES256-SHA:DES-CBC-SHA:RC4-SHA','AES256-SHA', test2); -} - -function test2() { - // Server has the preference of cipher suites where DES-CBC-SHA is in - // the first. - test(true, 'AES256-SHA:DES-CBC-SHA:RC4-SHA', 'DES-CBC-SHA', test3); -} - -function test3() { - // Server has the preference of cipher suites. RC4-SHA is given - // higher priority over DES-CBC-SHA among client cipher suites. - test(true, 'RC4-SHA:AES256-SHA', 'AES256-SHA', test4); -} - -function test4() { - // As client has only one cipher, server has no choice in regardless - // of honorCipherOrder. - test(true, 'RC4-SHA', 'RC4-SHA', test5); -} - -function test5() { - // Client did not explicitly set ciphers. Ensure that client defaults to - // sane ciphers. Even though server gives top priority to DES-CBC-SHA - // it should not be negotiated because it's not in default client ciphers. - test(true, null, 'AES256-SHA', test6); -} - -function test6() { - // Ensure that `tls.DEFAULT_CIPHERS` is used - SSL_Method = 'TLSv1_2_method'; - tls.DEFAULT_CIPHERS = 'ECDHE-RSA-AES256-SHA'; - test(true, null, 'ECDHE-RSA-AES256-SHA'); -} diff --git a/test/simple/test-tls-inception.js b/test/simple/test-tls-inception.js deleted file mode 100644 index d15d1ebd4..000000000 --- a/test/simple/test-tls-inception.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var fs = require('fs'); -var path = require('path'); -var net = require('net'); -var tls = require('tls'); -var assert = require('assert'); - -var options, a, b, portA, portB; -var gotHello = false; - -options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) -}; - -// the "proxy" server -a = tls.createServer(options, function (socket) { - var options = { - host: '127.0.0.1', - port: b.address().port, - rejectUnauthorized: false - }; - var dest = net.connect(options); - dest.pipe(socket); - socket.pipe(dest); -}); - -// the "target" server -b = tls.createServer(options, function (socket) { - socket.end('hello'); -}); - -process.on('exit', function () { - assert(gotHello); -}); - -a.listen(common.PORT, function () { - b.listen(common.PORT + 1, function () { - options = { - host: '127.0.0.1', - port: a.address().port, - rejectUnauthorized: false - }; - var socket = tls.connect(options); - var ssl; - ssl = tls.connect({ - socket: socket, - rejectUnauthorized: false - }); - ssl.setEncoding('utf8'); - ssl.once('data', function (data) { - assert.equal('hello', data); - gotHello = true; - }); - ssl.on('end', function () { - ssl.end(); - a.close(); - b.close(); - }); - }); -}); diff --git a/test/simple/test-tls-interleave.js b/test/simple/test-tls-interleave.js deleted file mode 100644 index 8bebb807e..000000000 --- a/test/simple/test-tls-interleave.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var tls = require('tls'); -var fs = require('fs'); - -var PORT = common.PORT; -var dir = common.fixturesDir; -var options = { key: fs.readFileSync(dir + '/test_key.pem'), - cert: fs.readFileSync(dir + '/test_cert.pem'), - ca: [ fs.readFileSync(dir + '/test_ca.pem') ] }; - -var writes = [ - 'some server data', - 'and a separate packet', - 'and one more', -]; -var receivedWrites = 0; - -var server = tls.createServer(options, function(c) { - writes.forEach(function(str) { - c.write(str); - }); -}).listen(PORT, function() { - var c = tls.connect(PORT, { rejectUnauthorized: false }, function() { - c.write('some client data'); - c.on('readable', function() { - var data = c.read(); - if (data === null) - return; - - data = data.toString(); - while (data.length !== 0) { - assert.strictEqual(data.indexOf(writes[receivedWrites]), 0); - data = data.slice(writes[receivedWrites].length); - - if (++receivedWrites === writes.length) { - c.end(); - server.close(); - } - } - }); - }); -}); - -process.on('exit', function() { - assert.equal(receivedWrites, writes.length); -}); diff --git a/test/simple/test-tls-invoke-queued.js b/test/simple/test-tls-invoke-queued.js deleted file mode 100644 index 3e877b406..000000000 --- a/test/simple/test-tls-invoke-queued.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var net = require('net'); -var tls = require('tls'); - -var common = require('../common'); - -var received = ''; -var ended = 0; - -var server = tls.createServer({ - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}, function(c) { - c._write('hello ', null, function() { - c._write('world!', null, function() { - c.destroy(); - }); - c._write(' gosh', null, function() {}); - }); - - server.close(); -}).listen(common.PORT, function() { - var c = tls.connect(common.PORT, { - rejectUnauthorized: false - }, function() { - c.on('data', function(chunk) { - received += chunk; - }); - c.on('end', function() { - ended++; - }); - }); -}); - -process.on('exit', function() { - assert.equal(ended, 1); - assert.equal(received, 'hello world! gosh'); -}); diff --git a/test/simple/test-tls-junk-closes-server.js b/test/simple/test-tls-junk-closes-server.js deleted file mode 100644 index 57db7f5a3..000000000 --- a/test/simple/test-tls-junk-closes-server.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var tls = require('tls'); -var fs = require('fs'); -var net = require('net'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') -}; - -var server = tls.createServer(options, function(s) { - s.write('welcome!\n'); - s.pipe(s); -}); - -server.listen(common.PORT, function() { - var c = net.createConnection(common.PORT); - - c.on('connect', function() { - c.write('blah\nblah\nblah\n'); - }); - - c.on('end', function() { - server.close(); - }); - -}); - diff --git a/test/simple/test-tls-key-mismatch.js b/test/simple/test-tls-key-mismatch.js deleted file mode 100644 index f99e9471f..000000000 --- a/test/simple/test-tls-key-mismatch.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') -}; - -var cert = null; - -assert.throws(function() { - tls.createSecureContext(options); -}); diff --git a/test/simple/test-tls-max-send-fragment.js b/test/simple/test-tls-max-send-fragment.js deleted file mode 100644 index f6fdf2512..000000000 --- a/test/simple/test-tls-max-send-fragment.js +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var net = require('net'); -var tls = require('tls'); - -var common = require('../common'); - -var buf = new Buffer(10000); -var received = 0; -var ended = 0; -var maxChunk = 768; - -var server = tls.createServer({ - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}, function(c) { - // Lower and upper limits - assert(!c.setMaxSendFragment(511)); - assert(!c.setMaxSendFragment(16385)); - - // Correct fragment size - assert(c.setMaxSendFragment(maxChunk)); - - c.end(buf); -}).listen(common.PORT, function() { - var c = tls.connect(common.PORT, { - rejectUnauthorized: false - }, function() { - c.on('data', function(chunk) { - assert(chunk.length <= maxChunk); - received += chunk.length; - }); - - // Ensure that we receive 'end' event anyway - c.on('end', function() { - ended++; - c.destroy(); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(ended, 1); - assert.equal(received, buf.length); -}); diff --git a/test/simple/test-tls-multi-key.js b/test/simple/test-tls-multi-key.js deleted file mode 100644 index e00c40409..000000000 --- a/test/simple/test-tls-multi-key.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: [ - fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem') - ], - cert: [ - fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), - fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') - ] -}; - -var ciphers = []; - -var server = tls.createServer(options, function(conn) { - conn.end('ok'); -}).listen(common.PORT, function() { - var ecdsa = tls.connect(common.PORT, { - ciphers: 'ECDHE-ECDSA-AES256-GCM-SHA384', - rejectUnauthorized: false - }, function() { - var rsa = tls.connect(common.PORT, { - ciphers: 'ECDHE-RSA-AES256-GCM-SHA384', - rejectUnauthorized: false - }, function() { - ecdsa.destroy(); - rsa.destroy(); - - ciphers.push(ecdsa.getCipher()); - ciphers.push(rsa.getCipher()); - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.deepEqual(ciphers, [{ - name: 'ECDHE-ECDSA-AES256-GCM-SHA384', - version: 'TLSv1/SSLv3' - }, { - name: 'ECDHE-RSA-AES256-GCM-SHA384', - version: 'TLSv1/SSLv3' - }]); -}); diff --git a/test/simple/test-tls-no-cert-required.js b/test/simple/test-tls-no-cert-required.js deleted file mode 100644 index 48e6c5940..000000000 --- a/test/simple/test-tls-no-cert-required.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var tls = require('tls'); - -// Omitting the cert or pfx option to tls.createServer() should not throw. -// AECDH-NULL-SHA is a no-authentication/no-encryption cipher and hence -// doesn't need a certificate. -tls.createServer({ ciphers: 'AECDH-NULL-SHA' }).listen(0, function() { - this.close(); -}); diff --git a/test/simple/test-tls-no-rsa-key.js b/test/simple/test-tls-no-rsa-key.js deleted file mode 100644 index d50eab942..000000000 --- a/test/simple/test-tls-no-rsa-key.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/ec-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') -}; - -var cert = null; - -var server = tls.createServer(options, function(conn) { - conn.end('ok'); -}).listen(common.PORT, function() { - var c = tls.connect(common.PORT, { - rejectUnauthorized: false - }, function() { - cert = c.getPeerCertificate(); - c.destroy(); - server.close(); - }); -}); - -process.on('exit', function() { - assert(cert); - assert.equal(cert.subject.C, 'US'); -}); diff --git a/test/simple/test-tls-npn-server-client.js b/test/simple/test-tls-npn-server-client.js deleted file mode 100644 index 0849cc8d2..000000000 --- a/test/simple/test-tls-npn-server-client.js +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.features.tls_npn) { - console.error('Skipping because node compiled without OpenSSL or ' + - 'with old OpenSSL version.'); - process.exit(0); -} - -var common = require('../common'), - assert = require('assert'), - fs = require('fs'), - tls = require('tls'); - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} - -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} - -var serverOptions = { - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), - crl: loadPEM('ca2-crl'), - SNICallback: function(servername, cb) { - cb(null, tls.createSecureContext({ - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), - crl: loadPEM('ca2-crl'), - })); - }, - NPNProtocols: ['a', 'b', 'c'] -}; - -var serverPort = common.PORT; - -var clientsOptions = [{ - port: serverPort, - key: serverOptions.key, - cert: serverOptions.cert, - crl: serverOptions.crl, - NPNProtocols: ['a', 'b', 'c'], - rejectUnauthorized: false -},{ - port: serverPort, - key: serverOptions.key, - cert: serverOptions.cert, - crl: serverOptions.crl, - NPNProtocols: ['c', 'b', 'e'], - rejectUnauthorized: false -},{ - port: serverPort, - key: serverOptions.key, - cert: serverOptions.cert, - crl: serverOptions.crl, - rejectUnauthorized: false -},{ - port: serverPort, - key: serverOptions.key, - cert: serverOptions.cert, - crl: serverOptions.crl, - NPNProtocols: ['first-priority-unsupported', 'x', 'y'], - rejectUnauthorized: false -}]; - -var serverResults = [], - clientsResults = []; - -var server = tls.createServer(serverOptions, function(c) { - serverResults.push(c.npnProtocol); -}); -server.listen(serverPort, startTest); - -function startTest() { - function connectClient(options, callback) { - var client = tls.connect(options, function() { - clientsResults.push(client.npnProtocol); - client.destroy(); - - callback(); - }); - }; - - connectClient(clientsOptions[0], function() { - connectClient(clientsOptions[1], function() { - connectClient(clientsOptions[2], function() { - connectClient(clientsOptions[3], function() { - server.close(); - }); - }); - }); - }); -} - -process.on('exit', function() { - assert.equal(serverResults[0], clientsResults[0]); - assert.equal(serverResults[1], clientsResults[1]); - assert.equal(serverResults[2], 'http/1.1'); - assert.equal(clientsResults[2], false); - assert.equal(serverResults[3], 'first-priority-unsupported'); - assert.equal(clientsResults[3], false); -}); diff --git a/test/simple/test-tls-ocsp-callback.js b/test/simple/test-tls-ocsp-callback.js deleted file mode 100644 index 4c7dd1d44..000000000 --- a/test/simple/test-tls-ocsp-callback.js +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!process.features.tls_ocsp) { - console.error('Skipping because node compiled without OpenSSL or ' + - 'with old OpenSSL version.'); - process.exit(0); -} -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var tls = require('tls'); -var constants = require('constants'); -var fs = require('fs'); -var join = require('path').join; - -test({ response: false }, function() { - test({ response: 'hello world' }, function() { - test({ ocsp: false }); - }); -}); - -function test(testOptions, cb) { - - var keyFile = join(common.fixturesDir, 'keys', 'agent1-key.pem'); - var certFile = join(common.fixturesDir, 'keys', 'agent1-cert.pem'); - var caFile = join(common.fixturesDir, 'keys', 'ca1-cert.pem'); - var key = fs.readFileSync(keyFile); - var cert = fs.readFileSync(certFile); - var ca = fs.readFileSync(caFile); - var options = { - key: key, - cert: cert, - ca: [ca] - }; - var requestCount = 0; - var clientSecure = 0; - var ocspCount = 0; - var ocspResponse; - var session; - - var server = tls.createServer(options, function(cleartext) { - cleartext.on('error', function(er) { - // We're ok with getting ECONNRESET in this test, but it's - // timing-dependent, and thus unreliable. Any other errors - // are just failures, though. - if (er.code !== 'ECONNRESET') - throw er; - }); - ++requestCount; - cleartext.end(); - }); - server.on('OCSPRequest', function(cert, issuer, callback) { - ++ocspCount; - assert.ok(Buffer.isBuffer(cert)); - assert.ok(Buffer.isBuffer(issuer)); - - // Just to check that async really works there - setTimeout(function() { - callback(null, - testOptions.response ? new Buffer(testOptions.response) : null); - }, 100); - }); - server.listen(common.PORT, function() { - var client = tls.connect({ - port: common.PORT, - requestOCSP: testOptions.ocsp !== false, - secureOptions: testOptions.ocsp === false ? - constants.SSL_OP_NO_TICKET : 0, - rejectUnauthorized: false - }, function() { - clientSecure++; - }); - client.on('OCSPResponse', function(resp) { - ocspResponse = resp; - if (resp) - client.destroy(); - }); - client.on('close', function() { - server.close(cb); - }); - }); - - process.on('exit', function() { - if (testOptions.ocsp === false) { - assert.equal(requestCount, clientSecure); - assert.equal(requestCount, 1); - return; - } - - if (testOptions.response) { - assert.equal(ocspResponse.toString(), testOptions.response); - } else { - assert.ok(ocspResponse === null); - } - assert.equal(requestCount, testOptions.response ? 0 : 1); - assert.equal(clientSecure, requestCount); - assert.equal(ocspCount, 1); - }); -} diff --git a/test/simple/test-tls-over-http-tunnel.js b/test/simple/test-tls-over-http-tunnel.js deleted file mode 100644 index 9fa82ae3e..000000000 --- a/test/simple/test-tls-over-http-tunnel.js +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); - -var fs = require('fs'); -var net = require('net'); -var http = require('http'); -var https = require('https'); - -var proxyPort = common.PORT + 1; -var gotRequest = false; - -var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); -var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); - -var options = { - key: key, - cert: cert -}; - -var server = https.createServer(options, function(req, res) { - console.log('SERVER: got request'); - res.writeHead(200, { - 'content-type': 'text/plain' - }); - console.log('SERVER: sending response'); - res.end('hello world\n'); -}); - -var proxy = net.createServer(function(clientSocket) { - console.log('PROXY: got a client connection'); - - var serverSocket = null; - - clientSocket.on('data', function(chunk) { - if (!serverSocket) { - // Verify the CONNECT request - assert.equal('CONNECT localhost:' + common.PORT + ' HTTP/1.1\r\n' + - 'Proxy-Connections: keep-alive\r\n' + - 'Host: localhost:' + proxyPort + '\r\n\r\n', - chunk); - - console.log('PROXY: got CONNECT request'); - console.log('PROXY: creating a tunnel'); - - // create the tunnel - serverSocket = net.connect(common.PORT, function() { - console.log('PROXY: replying to client CONNECT request'); - - // Send the response - clientSocket.write('HTTP/1.1 200 OK\r\nProxy-Connections: keep' + - '-alive\r\nConnections: keep-alive\r\nVia: ' + - 'localhost:' + proxyPort + '\r\n\r\n'); - }); - - serverSocket.on('data', function(chunk) { - clientSocket.write(chunk); - }); - - serverSocket.on('end', function() { - clientSocket.destroy(); - }); - } else { - serverSocket.write(chunk); - } - }); - - clientSocket.on('end', function() { - serverSocket.destroy(); - }); -}); - -server.listen(common.PORT); - -proxy.listen(proxyPort, function() { - console.log('CLIENT: Making CONNECT request'); - - var req = http.request({ - port: proxyPort, - method: 'CONNECT', - path: 'localhost:' + common.PORT, - headers: { - 'Proxy-Connections': 'keep-alive' - } - }); - req.useChunkedEncodingByDefault = false; // for v0.6 - req.on('response', onResponse); // for v0.6 - req.on('upgrade', onUpgrade); // for v0.6 - req.on('connect', onConnect); // for v0.7 or later - req.end(); - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } - - function onConnect(res, socket, header) { - assert.equal(200, res.statusCode); - console.log('CLIENT: got CONNECT response'); - - // detach the socket - socket.removeAllListeners('data'); - socket.removeAllListeners('close'); - socket.removeAllListeners('error'); - socket.removeAllListeners('drain'); - socket.removeAllListeners('end'); - socket.ondata = null; - socket.onend = null; - socket.ondrain = null; - - console.log('CLIENT: Making HTTPS request'); - - https.get({ - path: '/foo', - key: key, - cert: cert, - socket: socket, // reuse the socket - agent: false, - rejectUnauthorized: false - }, function(res) { - assert.equal(200, res.statusCode); - - res.on('data', function(chunk) { - assert.equal('hello world\n', chunk); - console.log('CLIENT: got HTTPS response'); - gotRequest = true; - }); - - res.on('end', function() { - proxy.close(); - server.close(); - }); - }).on('error', function(er) { - // We're ok with getting ECONNRESET in this test, but it's - // timing-dependent, and thus unreliable. Any other errors - // are just failures, though. - if (er.code !== 'ECONNRESET') - throw er; - }).end(); - } -}); - -process.on('exit', function() { - assert.ok(gotRequest); -}); diff --git a/test/simple/test-tls-passphrase.js b/test/simple/test-tls-passphrase.js deleted file mode 100644 index e9a5c5a5d..000000000 --- a/test/simple/test-tls-passphrase.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var path = require('path'); - -var key = fs.readFileSync(path.join(common.fixturesDir, 'pass-key.pem')); -var cert = fs.readFileSync(path.join(common.fixturesDir, 'pass-cert.pem')); - -var server = tls.Server({ - key: key, - passphrase: 'passphrase', - cert: cert, - ca: [cert], - requestCert: true, - rejectUnauthorized: true -}, function(s) { - s.end(); -}); - -var connectCount = 0; -server.listen(common.PORT, function() { - var c = tls.connect({ - port: common.PORT, - key: key, - passphrase: 'passphrase', - cert: cert, - rejectUnauthorized: false - }, function() { - ++connectCount; - }); - c.on('end', function() { - server.close(); - }); -}); - -assert.throws(function() { - tls.connect({ - port: common.PORT, - key: key, - passphrase: 'invalid', - cert: cert, - rejectUnauthorized: false - }); -}); - -process.on('exit', function() { - assert.equal(connectCount, 1); -}); diff --git a/test/simple/test-tls-pause.js b/test/simple/test-tls-pause.js deleted file mode 100644 index 5eaac8da1..000000000 --- a/test/simple/test-tls-pause.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var path = require('path'); - -var options = { - key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')), - cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) -}; - -var bufSize = 1024 * 1024; -var sent = 0; -var received = 0; - -var server = tls.Server(options, function(socket) { - socket.pipe(socket); - socket.on('data', function(c) { - console.error('data', c.length); - }); -}); - -server.listen(common.PORT, function() { - var resumed = false; - var client = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - console.error('connected'); - client.pause(); - common.debug('paused'); - send(); - function send() { - console.error('sending'); - var ret = client.write(new Buffer(bufSize)); - console.error('write => %j', ret); - if (false !== ret) { - console.error('write again'); - sent += bufSize; - assert.ok(sent < 100 * 1024 * 1024); // max 100MB - return process.nextTick(send); - } - sent += bufSize; - common.debug('sent: ' + sent); - resumed = true; - client.resume(); - console.error('resumed', client); - } - }); - client.on('data', function(data) { - console.error('data'); - assert.ok(resumed); - received += data.length; - console.error('received', received); - console.error('sent', sent); - if (received >= sent) { - common.debug('received: ' + received); - client.end(); - server.close(); - } - }); -}); - -process.on('exit', function() { - assert.equal(sent, received); -}); diff --git a/test/simple/test-tls-peer-certificate-encoding.js b/test/simple/test-tls-peer-certificate-encoding.js deleted file mode 100644 index 288236a93..000000000 --- a/test/simple/test-tls-peer-certificate-encoding.js +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var util = require('util'); -var join = require('path').join; -var spawn = require('child_process').spawn; - -var options = { - key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-key.pem')), - cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-cert.pem')), - ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca2-cert.pem')) ] -}; -var verified = false; - -var server = tls.createServer(options, function(cleartext) { - cleartext.end('World'); -}); -server.listen(common.PORT, function() { - var socket = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - var peerCert = socket.getPeerCertificate(); - - common.debug(util.inspect(peerCert)); - assert.equal(peerCert.subject.CN, 'Ádám Lippai'); - verified = true; - server.close(); - }); - socket.end('Hello'); -}); - -process.on('exit', function() { - assert.ok(verified); -}); diff --git a/test/simple/test-tls-peer-certificate-multi-keys.js b/test/simple/test-tls-peer-certificate-multi-keys.js deleted file mode 100644 index a321d2cba..000000000 --- a/test/simple/test-tls-peer-certificate-multi-keys.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var util = require('util'); -var join = require('path').join; -var spawn = require('child_process').spawn; - -var options = { - key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), - cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) -}; -var verified = false; - -var server = tls.createServer(options, function(cleartext) { - cleartext.end('World'); -}); -server.listen(common.PORT, function() { - var socket = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - var peerCert = socket.getPeerCertificate(); - common.debug(util.inspect(peerCert)); - assert.deepEqual(peerCert.subject.OU, - ['Information Technology', 'Engineering', 'Marketing']); - verified = true; - server.close(); - }); - socket.end('Hello'); -}); - -process.on('exit', function() { - assert.ok(verified); -}); diff --git a/test/simple/test-tls-peer-certificate.js b/test/simple/test-tls-peer-certificate.js deleted file mode 100644 index f1d0a7f19..000000000 --- a/test/simple/test-tls-peer-certificate.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); -var util = require('util'); -var join = require('path').join; -var spawn = require('child_process').spawn; - -var options = { - key: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-key.pem')), - cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), - ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] -}; -var verified = false; - -var server = tls.createServer(options, function(cleartext) { - cleartext.end('World'); -}); -server.listen(common.PORT, function() { - var socket = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }, function() { - var peerCert = socket.getPeerCertificate(); - assert.ok(!peerCert.issuerCertificate); - - // Verify that detailed return value has all certs - peerCert = socket.getPeerCertificate(true); - assert.ok(peerCert.issuerCertificate); - - common.debug(util.inspect(peerCert)); - assert.equal(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); - assert.equal(peerCert.serialNumber, '9A84ABCFB8A72ABE'); - assert.deepEqual(peerCert.infoAccess['OCSP - URI'], - [ 'http://ocsp.nodejs.org/' ]); - - var issuer = peerCert.issuerCertificate; - assert.ok(issuer.issuerCertificate === issuer); - assert.equal(issuer.serialNumber, 'B5090C899FC2FF93'); - verified = true; - server.close(); - }); - socket.end('Hello'); -}); - -process.on('exit', function() { - assert.ok(verified); -}); diff --git a/test/simple/test-tls-request-timeout.js b/test/simple/test-tls-request-timeout.js deleted file mode 100644 index 7f46bd213..000000000 --- a/test/simple/test-tls-request-timeout.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var hadTimeout = false; - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = tls.Server(options, function(socket) { - socket.setTimeout(100); - - socket.on('timeout', function(err) { - hadTimeout = true; - socket.end(); - server.close(); - }); -}); - -server.listen(common.PORT, function() { - var socket = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }); -}); - -process.on('exit', function() { - assert.ok(hadTimeout); -}); diff --git a/test/simple/test-tls-securepair-server.js b/test/simple/test-tls-securepair-server.js deleted file mode 100644 index ece965c54..000000000 --- a/test/simple/test-tls-securepair-server.js +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); - -var join = require('path').join; -var net = require('net'); -var fs = require('fs'); -var tls = require('tls'); -var spawn = require('child_process').spawn; - -var connections = 0; -var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); -var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); - -function log(a) { - console.error('***server*** ' + a); -} - -var server = net.createServer(function(socket) { - connections++; - log('connection fd=' + socket.fd); - var sslcontext = tls.createSecureContext({key: key, cert: cert}); - sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); - - var pair = tls.createSecurePair(sslcontext, true); - - assert.ok(pair.encrypted.writable); - assert.ok(pair.cleartext.writable); - - pair.encrypted.pipe(socket); - socket.pipe(pair.encrypted); - - log('i set it secure'); - - pair.on('secure', function() { - log('connected+secure!'); - pair.cleartext.write('hello\r\n'); - log(pair.cleartext.getPeerCertificate()); - log(pair.cleartext.getCipher()); - }); - - pair.cleartext.on('data', function(data) { - log('read bytes ' + data.length); - pair.cleartext.write(data); - }); - - socket.on('end', function() { - log('socket end'); - }); - - pair.cleartext.on('error', function(err) { - log('got error: '); - log(err); - log(err.stack); - socket.destroy(); - }); - - pair.encrypted.on('error', function(err) { - log('encrypted error: '); - log(err); - log(err.stack); - socket.destroy(); - }); - - socket.on('error', function(err) { - log('socket error: '); - log(err); - log(err.stack); - socket.destroy(); - }); - - socket.on('close', function(err) { - log('socket closed'); - }); - - pair.on('error', function(err) { - log('secure error: '); - log(err); - log(err.stack); - socket.destroy(); - }); -}); - -var gotHello = false; -var sentWorld = false; -var gotWorld = false; -var opensslExitCode = -1; - -server.listen(common.PORT, function() { - // To test use: openssl s_client -connect localhost:8000 - var client = spawn(common.opensslCli, ['s_client', '-connect', '127.0.0.1:' + - common.PORT]); - - - var out = ''; - - client.stdout.setEncoding('utf8'); - client.stdout.on('data', function(d) { - out += d; - - if (!gotHello && /hello/.test(out)) { - gotHello = true; - client.stdin.write('world\r\n'); - sentWorld = true; - } - - if (!gotWorld && /world/.test(out)) { - gotWorld = true; - client.stdin.end(); - } - }); - - client.stdout.pipe(process.stdout, { end: false }); - - client.on('exit', function(code) { - opensslExitCode = code; - server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(1, connections); - assert.ok(gotHello); - assert.ok(sentWorld); - assert.ok(gotWorld); - assert.equal(0, opensslExitCode); -}); diff --git a/test/simple/test-tls-server-verify.js b/test/simple/test-tls-server-verify.js deleted file mode 100644 index 085749af4..000000000 --- a/test/simple/test-tls-server-verify.js +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -// This is a rather complex test which sets up various TLS servers with node -// and connects to them using the 'openssl s_client' command line utility -// with various keys. Depending on the certificate authority and other -// parameters given to the server, the various clients are -// - rejected, -// - accepted and "unauthorized", or -// - accepted and "authorized". - -var testCases = - [{ title: 'Do not request certs. Everyone is unauthorized.', - requestCert: false, - rejectUnauthorized: false, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: false }, - { name: 'agent2', shouldReject: false, shouldAuth: false }, - { name: 'agent3', shouldReject: false, shouldAuth: false }, - { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Allow both authed and unauthed connections with CA1', - requestCert: true, - rejectUnauthorized: false, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, - { name: 'agent2', shouldReject: false, shouldAuth: false }, - { name: 'agent3', shouldReject: false, shouldAuth: false }, - { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Do not request certs at connection. Do that later', - requestCert: false, - rejectUnauthorized: false, - renegotiate: true, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, - { name: 'agent2', shouldReject: false, shouldAuth: false }, - { name: 'agent3', shouldReject: false, shouldAuth: false }, - { name: 'nocert', shouldReject: false, shouldAuth: false } - ] - }, - - { title: 'Allow only authed connections with CA1', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca1-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, - { name: 'agent2', shouldReject: true }, - { name: 'agent3', shouldReject: true }, - { name: 'nocert', shouldReject: true } - ] - }, - - { title: 'Allow only authed connections with CA1 and CA2', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca1-cert', 'ca2-cert'], - clients: - [{ name: 'agent1', shouldReject: false, shouldAuth: true }, - { name: 'agent2', shouldReject: true }, - { name: 'agent3', shouldReject: false, shouldAuth: true }, - { name: 'nocert', shouldReject: true } - ] - }, - - - { title: 'Allow only certs signed by CA2 but not in the CRL', - requestCert: true, - rejectUnauthorized: true, - renegotiate: false, - CAs: ['ca2-cert'], - crl: 'ca2-crl', - clients: - [ - { name: 'agent1', shouldReject: true, shouldAuth: false }, - { name: 'agent2', shouldReject: true, shouldAuth: false }, - { name: 'agent3', shouldReject: false, shouldAuth: true }, - // Agent4 has a cert in the CRL. - { name: 'agent4', shouldReject: true, shouldAuth: false }, - { name: 'nocert', shouldReject: true } - ] - } - ]; - - -var constants = require('constants'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); -var spawn = require('child_process').spawn; - - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} - - -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} - - -var serverKey = loadPEM('agent2-key'); -var serverCert = loadPEM('agent2-cert'); - - -function runClient(options, cb) { - - // Client can connect in three ways: - // - Self-signed cert - // - Certificate, but not signed by CA. - // - Certificate signed by CA. - - var args = ['s_client', '-connect', '127.0.0.1:' + common.PORT]; - - - console.log(' connecting with', options.name); - - switch (options.name) { - case 'agent1': - // Signed by CA1 - args.push('-key'); - args.push(filenamePEM('agent1-key')); - args.push('-cert'); - args.push(filenamePEM('agent1-cert')); - break; - - case 'agent2': - // Self-signed - // This is also the key-cert pair that the server will use. - args.push('-key'); - args.push(filenamePEM('agent2-key')); - args.push('-cert'); - args.push(filenamePEM('agent2-cert')); - break; - - case 'agent3': - // Signed by CA2 - args.push('-key'); - args.push(filenamePEM('agent3-key')); - args.push('-cert'); - args.push(filenamePEM('agent3-cert')); - break; - - case 'agent4': - // Signed by CA2 (rejected by ca2-crl) - args.push('-key'); - args.push(filenamePEM('agent4-key')); - args.push('-cert'); - args.push(filenamePEM('agent4-cert')); - break; - - case 'nocert': - // Do not send certificate - break; - - default: - throw new Error('Unknown agent name'); - } - - // To test use: openssl s_client -connect localhost:8000 - var client = spawn(common.opensslCli, args); - - var out = ''; - - var rejected = true; - var authed = false; - var goodbye = false; - - client.stdout.setEncoding('utf8'); - client.stdout.on('data', function(d) { - out += d; - - if (!goodbye && /_unauthed/g.test(out)) { - console.error(' * unauthed'); - goodbye = true; - client.stdin.end('goodbye\n'); - authed = false; - rejected = false; - } - - if (!goodbye && /_authed/g.test(out)) { - console.error(' * authed'); - goodbye = true; - client.stdin.end('goodbye\n'); - authed = true; - rejected = false; - } - }); - - //client.stdout.pipe(process.stdout); - - client.on('exit', function(code) { - //assert.equal(0, code, options.name + - // ": s_client exited with error code " + code); - if (options.shouldReject) { - assert.equal(true, rejected, options.name + - ' NOT rejected, but should have been'); - } else { - assert.equal(false, rejected, options.name + - ' rejected, but should NOT have been'); - assert.equal(options.shouldAuth, authed); - } - - cb(); - }); -} - - -// Run the tests -var successfulTests = 0; -function runTest(testIndex) { - var tcase = testCases[testIndex]; - if (!tcase) return; - - console.error("Running '%s'", tcase.title); - - var cas = tcase.CAs.map(loadPEM); - - var crl = tcase.crl ? loadPEM(tcase.crl) : null; - - var serverOptions = { - key: serverKey, - cert: serverCert, - ca: cas, - crl: crl, - requestCert: tcase.requestCert, - rejectUnauthorized: tcase.rejectUnauthorized - }; - - var connections = 0; - - /* - * If renegotiating - session might be resumed and openssl won't request - * client's certificate (probably because of bug in the openssl) - */ - if (tcase.renegotiate) { - serverOptions.secureOptions = - constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - } - - var renegotiated = false; - var server = tls.Server(serverOptions, function handleConnection(c) { - if (tcase.renegotiate && !renegotiated) { - renegotiated = true; - setTimeout(function() { - console.error('- connected, renegotiating'); - c.write('\n_renegotiating\n'); - return c.renegotiate({ - requestCert: true, - rejectUnauthorized: false - }, function(err) { - assert(!err); - c.write('\n_renegotiated\n'); - handleConnection(c); - }); - }, 200); - return; - } - - connections++; - if (c.authorized) { - console.error('- authed connection: ' + - c.getPeerCertificate().subject.CN); - c.write('\n_authed\n'); - } else { - console.error('- unauthed connection: %s', c.authorizationError); - c.write('\n_unauthed\n'); - } - }); - - function runNextClient(clientIndex) { - var options = tcase.clients[clientIndex]; - if (options) { - runClient(options, function() { - runNextClient(clientIndex + 1); - }); - } else { - server.close(); - successfulTests++; - runTest(testIndex + 1); - } - } - - server.listen(common.PORT, function() { - if (tcase.debug) { - console.error('TLS server running on port ' + common.PORT); - } else { - runNextClient(0); - } - }); -} - - -runTest(0); - - -process.on('exit', function() { - assert.equal(successfulTests, testCases.length); -}); diff --git a/test/simple/test-tls-session-cache.js b/test/simple/test-tls-session-cache.js deleted file mode 100644 index d5db30ce1..000000000 --- a/test/simple/test-tls-session-cache.js +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -doTest({ tickets: false } , function() { - doTest({ tickets: true } , function() { - console.error('all done'); - }); -}); - -function doTest(testOptions, callback) { - var assert = require('assert'); - var tls = require('tls'); - var fs = require('fs'); - var join = require('path').join; - var spawn = require('child_process').spawn; - - var keyFile = join(common.fixturesDir, 'agent.key'); - var certFile = join(common.fixturesDir, 'agent.crt'); - var key = fs.readFileSync(keyFile); - var cert = fs.readFileSync(certFile); - var options = { - key: key, - cert: cert, - ca: [cert], - requestCert: true - }; - var requestCount = 0; - var resumeCount = 0; - var session; - - var server = tls.createServer(options, function(cleartext) { - cleartext.on('error', function(er) { - // We're ok with getting ECONNRESET in this test, but it's - // timing-dependent, and thus unreliable. Any other errors - // are just failures, though. - if (er.code !== 'ECONNRESET') - throw er; - }); - ++requestCount; - cleartext.end(); - }); - server.on('newSession', function(id, data, cb) { - // Emulate asynchronous store - setTimeout(function() { - assert.ok(!session); - session = { - id: id, - data: data - }; - cb(); - }, 1000); - }); - server.on('resumeSession', function(id, callback) { - ++resumeCount; - assert.ok(session); - assert.equal(session.id.toString('hex'), id.toString('hex')); - - // Just to check that async really works there - setTimeout(function() { - callback(null, session.data); - }, 100); - }); - server.listen(common.PORT, function() { - var client = spawn(common.opensslCli, [ - 's_client', - '-tls1', - '-connect', 'localhost:' + common.PORT, - '-servername', 'ohgod', - '-key', join(common.fixturesDir, 'agent.key'), - '-cert', join(common.fixturesDir, 'agent.crt'), - '-reconnect' - ].concat(testOptions.tickets ? [] : '-no_ticket'), { - stdio: [ 0, 1, 'pipe' ] - }); - var err = ''; - client.stderr.setEncoding('utf8'); - client.stderr.on('data', function(chunk) { - err += chunk; - }); - client.on('exit', function(code) { - console.error('done'); - assert.equal(code, 0); - server.close(function() { - setTimeout(callback, 100); - }); - }); - }); - - process.on('exit', function() { - if (testOptions.tickets) { - assert.equal(requestCount, 6); - assert.equal(resumeCount, 0); - } else { - // initial request + reconnect requests (5 times) - assert.ok(session); - assert.equal(requestCount, 6); - assert.equal(resumeCount, 5); - } - }); -} diff --git a/test/simple/test-tls-set-ciphers.js b/test/simple/test-tls-set-ciphers.js deleted file mode 100644 index 1571d5e83..000000000 --- a/test/simple/test-tls-set-ciphers.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); - -if (!common.opensslCli) { - console.error('Skipping because node compiled without OpenSSL CLI.'); - process.exit(0); -} - -var assert = require('assert'); -var exec = require('child_process').exec; -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), - ciphers: 'RC4-MD5' -}; - -var reply = 'I AM THE WALRUS'; // something recognizable -var nconns = 0; -var response = ''; - -process.on('exit', function() { - assert.equal(nconns, 1); - assert.notEqual(response.indexOf(reply), -1); -}); - -var server = tls.createServer(options, function(conn) { - conn.end(reply); - nconns++; -}); - -server.listen(common.PORT, '127.0.0.1', function() { - var cmd = common.opensslCli + ' s_client -cipher ' + options.ciphers + - ' -connect 127.0.0.1:' + common.PORT; - - exec(cmd, function(err, stdout, stderr) { - if (err) throw err; - response = stdout; - server.close(); - }); -}); diff --git a/test/simple/test-tls-set-encoding.js b/test/simple/test-tls-set-encoding.js deleted file mode 100644 index 0f6beafd1..000000000 --- a/test/simple/test-tls-set-encoding.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') -}; - -var connections = 0; -var message = 'hello world\n'; - - -var server = tls.Server(options, function(socket) { - socket.end(message); - connections++; -}); - - -server.listen(common.PORT, function() { - var client = tls.connect({ - port: common.PORT, - rejectUnauthorized: false - }); - - var buffer = ''; - - client.setEncoding('utf8'); - - client.on('data', function(d) { - assert.ok(typeof d === 'string'); - buffer += d; - }); - - - client.on('close', function() { - // readyState is deprecated but we want to make - // sure this isn't triggering an assert in lib/net.js - // See issue #1069. - assert.equal('closed', client.readyState); - - assert.equal(buffer, message); - console.log(message); - server.close(); - }); -}); - - -process.on('exit', function() { - assert.equal(1, connections); -}); diff --git a/test/simple/test-tls-sni-option.js b/test/simple/test-tls-sni-option.js deleted file mode 100644 index 57c17163a..000000000 --- a/test/simple/test-tls-sni-option.js +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.features.tls_sni) { - console.error('Skipping because node compiled without OpenSSL or ' + - 'with old OpenSSL version.'); - process.exit(0); -} - -var common = require('../common'), - assert = require('assert'), - fs = require('fs'), - tls = require('tls'); - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} - -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} - -var serverOptions = { - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), - SNICallback: function(servername, callback) { - var context = SNIContexts[servername]; - - // Just to test asynchronous callback - setTimeout(function() { - if (context) { - if (context.emptyRegression) - callback(null, {}); - else - callback(null, tls.createSecureContext(context)); - } else { - callback(null, null); - } - }, 100); - } -}; - -var SNIContexts = { - 'a.example.com': { - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert') - }, - 'b.example.com': { - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert') - }, - 'c.another.com': { - emptyRegression: true - } -}; - -var serverPort = common.PORT; - -var clientsOptions = [{ - port: serverPort, - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert'), - ca: [loadPEM('ca1-cert')], - servername: 'a.example.com', - rejectUnauthorized: false -}, { - port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), - ca: [loadPEM('ca2-cert')], - servername: 'b.example.com', - rejectUnauthorized: false -}, { - port: serverPort, - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert'), - ca: [loadPEM('ca1-cert')], - servername: 'c.wrong.com', - rejectUnauthorized: false -}, { - port: serverPort, - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert'), - ca: [loadPEM('ca1-cert')], - servername: 'c.another.com', - rejectUnauthorized: false -}]; - -var serverResults = [], - clientResults = [], - serverErrors = [], - clientErrors = [], - serverError, - clientError; - -var server = tls.createServer(serverOptions, function(c) { - serverResults.push(c.servername); -}); - -server.on('clientError', function(err) { - serverResults.push(null); - serverError = err.message; -}); - -server.listen(serverPort, startTest); - -function startTest() { - function connectClient(i, callback) { - var options = clientsOptions[i]; - clientError = null; - serverError = null; - - var client = tls.connect(options, function() { - clientResults.push( - /Hostname\/IP doesn't/.test(client.authorizationError || '')); - client.destroy(); - - next(); - }); - - client.on('error', function(err) { - clientResults.push(false); - clientError = err.message; - next(); - }); - - function next() { - clientErrors.push(clientError); - serverErrors.push(serverError); - - if (i === clientsOptions.length - 1) - callback(); - else - connectClient(i + 1, callback); - } - }; - - connectClient(0, function() { - server.close(); - }); -} - -process.on('exit', function() { - assert.deepEqual(serverResults, ['a.example.com', 'b.example.com', - 'c.wrong.com', null]); - assert.deepEqual(clientResults, [true, true, false, false]); - assert.deepEqual(clientErrors, [null, null, null, "socket hang up"]); - assert.deepEqual(serverErrors, [null, null, null, "Invalid SNI context"]); -}); diff --git a/test/simple/test-tls-sni-server-client.js b/test/simple/test-tls-sni-server-client.js deleted file mode 100644 index 31fc41942..000000000 --- a/test/simple/test-tls-sni-server-client.js +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -if (!process.features.tls_sni) { - console.error('Skipping because node compiled without OpenSSL or ' + - 'with old OpenSSL version.'); - process.exit(0); -} - -var common = require('../common'), - assert = require('assert'), - fs = require('fs'), - tls = require('tls'); - -function filenamePEM(n) { - return require('path').join(common.fixturesDir, 'keys', n + '.pem'); -} - -function loadPEM(n) { - return fs.readFileSync(filenamePEM(n)); -} - -var serverOptions = { - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert') -}; - -var SNIContexts = { - 'a.example.com': { - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert') - }, - 'asterisk.test.com': { - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert') - } -}; - -var serverPort = common.PORT; - -var clientsOptions = [{ - port: serverPort, - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert'), - ca: [loadPEM('ca1-cert')], - servername: 'a.example.com', - rejectUnauthorized: false -}, { - port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), - ca: [loadPEM('ca2-cert')], - servername: 'b.test.com', - rejectUnauthorized: false -}, { - port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), - ca: [loadPEM('ca2-cert')], - servername: 'a.b.test.com', - rejectUnauthorized: false -}, { - port: serverPort, - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert'), - ca: [loadPEM('ca1-cert')], - servername: 'c.wrong.com', - rejectUnauthorized: false -}]; - -var serverResults = [], - clientResults = []; - -var server = tls.createServer(serverOptions, function(c) { - serverResults.push(c.servername); -}); - -server.addContext('a.example.com', SNIContexts['a.example.com']); -server.addContext('*.test.com', SNIContexts['asterisk.test.com']); - -server.listen(serverPort, startTest); - -function startTest() { - var i = 0; - function start() { - // No options left - if (i === clientsOptions.length) - return server.close(); - - var options = clientsOptions[i++]; - var client = tls.connect(options, function() { - clientResults.push( - client.authorizationError && - /Hostname\/IP doesn't/.test(client.authorizationError)); - client.destroy(); - - // Continue - start(); - }); - }; - - start(); -} - -process.on('exit', function() { - assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', - 'a.b.test.com', 'c.wrong.com']); - assert.deepEqual(clientResults, [true, true, false, false]); -}); diff --git a/test/simple/test-tls-ticket-cluster.js b/test/simple/test-tls-ticket-cluster.js deleted file mode 100644 index 22fe10c42..000000000 --- a/test/simple/test-tls-ticket-cluster.js +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var cluster = require('cluster'); -var tls = require('tls'); -var fs = require('fs'); -var join = require('path').join; - -var workerCount = 4; -var expectedReqCount = 16; - -if (cluster.isMaster) { - var reusedCount = 0; - var reqCount = 0; - var lastSession = null; - var shootOnce = false; - - function shoot() { - console.error('[master] connecting'); - var c = tls.connect(common.PORT, { - session: lastSession, - rejectUnauthorized: false - }, function() { - lastSession = c.getSession(); - c.end(); - - if (++reqCount === expectedReqCount) { - Object.keys(cluster.workers).forEach(function(id) { - cluster.workers[id].send('die'); - }); - } else { - shoot(); - } - }); - } - - function fork() { - var worker = cluster.fork(); - var workerReqCount = 0; - worker.on('message', function(msg) { - console.error('[master] got %j', msg); - if (msg === 'reused') { - ++reusedCount; - } else if (msg === 'listening' && !shootOnce) { - shootOnce = true; - shoot(); - } - }); - - worker.on('exit', function() { - console.error('[master] worker died'); - }); - } - for (var i = 0; i < workerCount; i++) { - fork(); - } - - process.on('exit', function() { - assert.equal(reqCount, expectedReqCount); - assert.equal(reusedCount + 1, reqCount); - }); - return; -} - -var keyFile = join(common.fixturesDir, 'agent.key'); -var certFile = join(common.fixturesDir, 'agent.crt'); -var key = fs.readFileSync(keyFile); -var cert = fs.readFileSync(certFile); -var options = { - key: key, - cert: cert -}; - -var server = tls.createServer(options, function(c) { - if (c.isSessionReused()) { - process.send('reused'); - } else { - process.send('not-reused'); - } - c.end(); -}); - -server.listen(common.PORT, function() { - process.send('listening'); -}); - -process.on('message', function listener(msg) { - console.error('[worker] got %j', msg); - if (msg === 'die') { - server.close(function() { - console.error('[worker] server close'); - - process.exit(); - }); - } -}); - -process.on('exit', function() { - console.error('[worker] exit'); -}); diff --git a/test/simple/test-tls-ticket.js b/test/simple/test-tls-ticket.js deleted file mode 100644 index 471d8c3ce..000000000 --- a/test/simple/test-tls-ticket.js +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var assert = require('assert'); -var fs = require('fs'); -var net = require('net'); -var tls = require('tls'); -var crypto = require('crypto'); - -var common = require('../common'); - -var keys = crypto.randomBytes(48); -var serverLog = []; -var ticketLog = []; - -var serverCount = 0; -function createServer() { - var id = serverCount++; - - var server = tls.createServer({ - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), - ticketKeys: keys - }, function(c) { - serverLog.push(id); - c.end(); - }); - - return server; -} - -var servers = [ createServer(), createServer(), createServer(), createServer(), createServer(), createServer() ]; - -// Create one TCP server and balance sockets to multiple TLS server instances -var shared = net.createServer(function(c) { - servers.shift().emit('connection', c); -}).listen(common.PORT, function() { - start(function() { - shared.close(); - }); -}); - -function start(callback) { - var sess = null; - var left = servers.length; - - function connect() { - var s = tls.connect(common.PORT, { - session: sess, - rejectUnauthorized: false - }, function() { - sess = s.getSession() || sess; - ticketLog.push(s.getTLSTicket().toString('hex')); - }); - s.on('close', function() { - if (--left === 0) - callback(); - else - connect(); - }); - } - - connect(); -} - -process.on('exit', function() { - assert.equal(ticketLog.length, serverLog.length); - for (var i = 0; i < serverLog.length - 1; i++) { - assert.notEqual(serverLog[i], serverLog[i + 1]); - assert.equal(ticketLog[i], ticketLog[i + 1]); - } -}); diff --git a/test/simple/test-tls-timeout-server-2.js b/test/simple/test-tls-timeout-server-2.js deleted file mode 100644 index dfa9be3de..000000000 --- a/test/simple/test-tls-timeout-server-2.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) process.exit(); - -var common = require('../common'); -var assert = require('assert'); -var tls = require('tls'); -var fs = require('fs'); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') -}; - -var server = tls.createServer(options, function(cleartext) { - cleartext.setTimeout(50, function() { - cleartext.destroy(); - server.close(); - }); -}); - -server.listen(common.PORT, function() { - tls.connect({ - host: '127.0.0.1', - port: common.PORT, - rejectUnauthorized: false - }); -}); diff --git a/test/simple/test-tls-timeout-server.js b/test/simple/test-tls-timeout-server.js deleted file mode 100644 index 2c9b973ab..000000000 --- a/test/simple/test-tls-timeout-server.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) process.exit(); - -var common = require('../common'); -var assert = require('assert'); -var net = require('net'); -var tls = require('tls'); -var fs = require('fs'); - -var clientErrors = 0; - -process.on('exit', function() { - assert.equal(clientErrors, 1); -}); - -var options = { - key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), - cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), - handshakeTimeout: 50 -}; - -var server = tls.createServer(options, assert.fail); - -server.on('clientError', function(err, conn) { - conn.destroy(); - server.close(); - clientErrors++; -}); - -server.listen(common.PORT, function() { - net.connect({ host: '127.0.0.1', port: common.PORT }); -}); diff --git a/test/simple/test-tls-zero-clear-in.js b/test/simple/test-tls-zero-clear-in.js deleted file mode 100644 index 22f45b663..000000000 --- a/test/simple/test-tls-zero-clear-in.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -if (!process.versions.openssl) { - console.error('Skipping because node compiled without OpenSSL.'); - process.exit(0); -} - -var common = require('../common'); -var assert = require('assert'); -var fs = require('fs'); -var tls = require('tls'); -var path = require('path'); - -var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); -var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - -var errorEmitted = false; - -var server = tls.createServer({ - cert: cert, - key: key -}, function(c) { - // Nop - setTimeout(function() { - c.destroy(); - server.close(); - }, 20); -}).listen(common.PORT, function() { - var conn = tls.connect({ - cert: cert, - key: key, - rejectUnauthorized: false, - port: common.PORT - }, function() { - setTimeout(function() { - conn.destroy(); - }, 20); - }); - - // SSL_write() call's return value, when called 0 bytes, should not be - // treated as error. - conn.end(''); - - conn.on('error', function(err) { - console.log(err); - errorEmitted = true; - }); -}); - -process.on('exit', function() { - assert.ok(!errorEmitted); -}); diff --git a/test/simple/test-tty-stdout-end.js b/test/simple/test-tty-stdout-end.js deleted file mode 100644 index 1fc279068..000000000 --- a/test/simple/test-tty-stdout-end.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Can't test this when 'make test' doesn't assign a tty to the stdout. -var common = require('../common'); -var assert = require('assert'); - -var exceptionCaught = false; - -try { - process.stdout.end(); -} catch (e) { - exceptionCaught = true; - assert.ok(common.isError(e)); - assert.equal('process.stdout cannot be closed.', e.message); -} - -assert.ok(exceptionCaught); diff --git a/test/simple/test-tty-wrap.js b/test/simple/test-tty-wrap.js deleted file mode 100644 index 610b92b43..000000000 --- a/test/simple/test-tty-wrap.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var TTY = process.binding('tty_wrap').TTY; -var isTTY = process.binding('tty_wrap').isTTY; - -if (isTTY(1) == false) { - console.error('fd 1 is not a tty. skipping test.'); - process.exit(0); -} - -var handle = new TTY(1); -var callbacks = 0; - -var req1 = handle.writeBuffer(Buffer('hello world\n')); -req1.oncomplete = function() { - callbacks++; -}; - -var req2 = handle.writeBuffer(Buffer('hello world\n')); -req2.oncomplete = function() { - callbacks++; -}; - -process.on('exit', function() { - assert.equal(2, callbacks); -}); diff --git a/test/simple/test-umask.js b/test/simple/test-umask.js deleted file mode 100644 index a41c46b55..000000000 --- a/test/simple/test-umask.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// Note in Windows one can only set the "user" bits. -var mask; -if (process.platform == 'win32') { - mask = '0600'; -} else { - mask = '0664'; -} - -var old = process.umask(mask); - -assert.equal(parseInt(mask, 8), process.umask(old)); - -// confirm reading the umask does not modify it. -// 1. If the test fails, this call will succeed, but the mask will be set to 0 -assert.equal(old, process.umask()); -// 2. If the test fails, process.umask() will return 0 -assert.equal(old, process.umask()); diff --git a/test/simple/test-url.js b/test/simple/test-url.js deleted file mode 100644 index f12a00dbe..000000000 --- a/test/simple/test-url.js +++ /dev/null @@ -1,1625 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var url = require('url'), - util = require('util'); - -// URLs to parse, and expected data -// { url : parsed } -var parseTests = { - '//some_path' : { - 'href': '//some_path', - 'pathname': '//some_path', - 'path': '//some_path' - }, - - 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h': { - protocol: 'http:', - slashes: true, - host: 'evil-phisher', - hostname: 'evil-phisher', - pathname: '/foo.html', - path: '/foo.html', - hash: '#h%5Ca%5Cs%5Ch', - href: 'http://evil-phisher/foo.html#h%5Ca%5Cs%5Ch' - }, - - 'http:\\\\evil-phisher\\foo.html?json="\\"foo\\""#h\\a\\s\\h': { - protocol: 'http:', - slashes: true, - host: 'evil-phisher', - hostname: 'evil-phisher', - pathname: '/foo.html', - search: '?json=%22%5C%22foo%5C%22%22', - query: 'json=%22%5C%22foo%5C%22%22', - path: '/foo.html?json=%22%5C%22foo%5C%22%22', - hash: '#h%5Ca%5Cs%5Ch', - href: 'http://evil-phisher/foo.html?json=%22%5C%22foo%5C%22%22#h%5Ca%5Cs%5Ch' - }, - - 'http:\\\\evil-phisher\\foo.html#h\\a\\s\\h?blarg': { - protocol: 'http:', - slashes: true, - host: 'evil-phisher', - hostname: 'evil-phisher', - pathname: '/foo.html', - path: '/foo.html', - hash: '#h%5Ca%5Cs%5Ch?blarg', - href: 'http://evil-phisher/foo.html#h%5Ca%5Cs%5Ch?blarg' - }, - - - 'http:\\\\evil-phisher\\foo.html': { - protocol: 'http:', - slashes: true, - host: 'evil-phisher', - hostname: 'evil-phisher', - pathname: '/foo.html', - path: '/foo.html', - href: 'http://evil-phisher/foo.html' - }, - - 'HTTP://www.example.com/' : { - 'href': 'http://www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'HTTP://www.example.com' : { - 'href': 'http://www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://www.ExAmPlE.com/' : { - 'href': 'http://www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://user:pw@www.ExAmPlE.com/' : { - 'href': 'http://user:pw@www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:pw', - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://USER:PW@www.ExAmPlE.com/' : { - 'href': 'http://USER:PW@www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'auth': 'USER:PW', - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://user@www.example.com/' : { - 'href': 'http://user@www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user', - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://user%3Apw@www.example.com/' : { - 'href': 'http://user:pw@www.example.com/', - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:pw', - 'host': 'www.example.com', - 'hostname': 'www.example.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://x.com/path?that\'s#all, folks' : { - 'href': 'http://x.com/path?that%27s#all,%20folks', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x.com', - 'hostname': 'x.com', - 'search': '?that%27s', - 'query': 'that%27s', - 'pathname': '/path', - 'hash': '#all,%20folks', - 'path': '/path?that%27s' - }, - - 'HTTP://X.COM/Y' : { - 'href': 'http://x.com/Y', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x.com', - 'hostname': 'x.com', - 'pathname': '/Y', - 'path': '/Y' - }, - - // + not an invalid host character - // per https://url.spec.whatwg.org/#host-parsing - 'http://x.y.com+a/b/c' : { - 'href': 'http://x.y.com+a/b/c', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x.y.com+a', - 'hostname': 'x.y.com+a', - 'pathname': '/b/c', - 'path': '/b/c' - }, - - // an unexpected invalid char in the hostname. - 'HtTp://x.y.cOm;a/b/c?d=e#f gi' : { - 'href': 'http://x.y.com/;a/b/c?d=e#f%20g%3Ch%3Ei', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x.y.com', - 'hostname': 'x.y.com', - 'pathname': ';a/b/c', - 'search': '?d=e', - 'query': 'd=e', - 'hash': '#f%20g%3Ch%3Ei', - 'path': ';a/b/c?d=e' - }, - - // make sure that we don't accidentally lcast the path parts. - 'HtTp://x.y.cOm;A/b/c?d=e#f gi' : { - 'href': 'http://x.y.com/;A/b/c?d=e#f%20g%3Ch%3Ei', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x.y.com', - 'hostname': 'x.y.com', - 'pathname': ';A/b/c', - 'search': '?d=e', - 'query': 'd=e', - 'hash': '#f%20g%3Ch%3Ei', - 'path': ';A/b/c?d=e' - }, - - 'http://x...y...#p': { - 'href': 'http://x...y.../#p', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x...y...', - 'hostname': 'x...y...', - 'hash': '#p', - 'pathname': '/', - 'path': '/' - }, - - 'http://x/p/"quoted"': { - 'href': 'http://x/p/%22quoted%22', - 'protocol': 'http:', - 'slashes': true, - 'host': 'x', - 'hostname': 'x', - 'pathname': '/p/%22quoted%22', - 'path': '/p/%22quoted%22' - }, - - ' Is a URL!': { - 'href': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', - 'pathname': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!', - 'path': '%3Chttp://goo.corn/bread%3E%20Is%20a%20URL!' - }, - - 'http://www.narwhaljs.org/blog/categories?id=news' : { - 'href': 'http://www.narwhaljs.org/blog/categories?id=news', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.narwhaljs.org', - 'hostname': 'www.narwhaljs.org', - 'search': '?id=news', - 'query': 'id=news', - 'pathname': '/blog/categories', - 'path': '/blog/categories?id=news' - }, - - 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' : { - 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', - 'protocol': 'http:', - 'slashes': true, - 'host': 'mt0.google.com', - 'hostname': 'mt0.google.com', - 'pathname': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=', - 'path': '/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=' - }, - - 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' : { - 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api' + - '&x=2&y=2&z=3&s=', - 'protocol': 'http:', - 'slashes': true, - 'host': 'mt0.google.com', - 'hostname': 'mt0.google.com', - 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', - 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', - 'pathname': '/vt/lyrs=m@114', - 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' - }, - - 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=': - { - 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???' + - '&hl=en&src=api&x=2&y=2&z=3&s=', - 'protocol': 'http:', - 'slashes': true, - 'host': 'mt0.google.com', - 'auth': 'user:pass', - 'hostname': 'mt0.google.com', - 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=', - 'query': '??&hl=en&src=api&x=2&y=2&z=3&s=', - 'pathname': '/vt/lyrs=m@114', - 'path': '/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=' - }, - - 'file:///etc/passwd' : { - 'href': 'file:///etc/passwd', - 'slashes': true, - 'protocol': 'file:', - 'pathname': '/etc/passwd', - 'hostname': '', - 'host': '', - 'path': '/etc/passwd' - }, - - 'file://localhost/etc/passwd' : { - 'href': 'file://localhost/etc/passwd', - 'protocol': 'file:', - 'slashes': true, - 'pathname': '/etc/passwd', - 'hostname': 'localhost', - 'host': 'localhost', - 'path': '/etc/passwd' - }, - - 'file://foo/etc/passwd' : { - 'href': 'file://foo/etc/passwd', - 'protocol': 'file:', - 'slashes': true, - 'pathname': '/etc/passwd', - 'hostname': 'foo', - 'host': 'foo', - 'path': '/etc/passwd' - }, - - 'file:///etc/node/' : { - 'href': 'file:///etc/node/', - 'slashes': true, - 'protocol': 'file:', - 'pathname': '/etc/node/', - 'hostname': '', - 'host': '', - 'path': '/etc/node/' - }, - - 'file://localhost/etc/node/' : { - 'href': 'file://localhost/etc/node/', - 'protocol': 'file:', - 'slashes': true, - 'pathname': '/etc/node/', - 'hostname': 'localhost', - 'host': 'localhost', - 'path': '/etc/node/' - }, - - 'file://foo/etc/node/' : { - 'href': 'file://foo/etc/node/', - 'protocol': 'file:', - 'slashes': true, - 'pathname': '/etc/node/', - 'hostname': 'foo', - 'host': 'foo', - 'path': '/etc/node/' - }, - - 'http:/baz/../foo/bar' : { - 'href': 'http:/baz/../foo/bar', - 'protocol': 'http:', - 'pathname': '/baz/../foo/bar', - 'path': '/baz/../foo/bar' - }, - - 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : { - 'href': 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag', - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com:8000', - 'auth': 'user:pass', - 'port': '8000', - 'hostname': 'example.com', - 'hash': '#frag', - 'search': '?baz=quux', - 'query': 'baz=quux', - 'pathname': '/foo/bar', - 'path': '/foo/bar?baz=quux' - }, - - '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : { - 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag', - 'slashes': true, - 'host': 'example.com:8000', - 'auth': 'user:pass', - 'port': '8000', - 'hostname': 'example.com', - 'hash': '#frag', - 'search': '?baz=quux', - 'query': 'baz=quux', - 'pathname': '/foo/bar', - 'path': '/foo/bar?baz=quux' - }, - - '/foo/bar?baz=quux#frag' : { - 'href': '/foo/bar?baz=quux#frag', - 'hash': '#frag', - 'search': '?baz=quux', - 'query': 'baz=quux', - 'pathname': '/foo/bar', - 'path': '/foo/bar?baz=quux' - }, - - 'http:/foo/bar?baz=quux#frag' : { - 'href': 'http:/foo/bar?baz=quux#frag', - 'protocol': 'http:', - 'hash': '#frag', - 'search': '?baz=quux', - 'query': 'baz=quux', - 'pathname': '/foo/bar', - 'path': '/foo/bar?baz=quux' - }, - - 'mailto:foo@bar.com?subject=hello' : { - 'href': 'mailto:foo@bar.com?subject=hello', - 'protocol': 'mailto:', - 'host': 'bar.com', - 'auth' : 'foo', - 'hostname' : 'bar.com', - 'search': '?subject=hello', - 'query': 'subject=hello', - 'path': '?subject=hello' - }, - - 'javascript:alert(\'hello\');' : { - 'href': 'javascript:alert(\'hello\');', - 'protocol': 'javascript:', - 'pathname': 'alert(\'hello\');', - 'path': 'alert(\'hello\');' - }, - - 'xmpp:isaacschlueter@jabber.org' : { - 'href': 'xmpp:isaacschlueter@jabber.org', - 'protocol': 'xmpp:', - 'host': 'jabber.org', - 'auth': 'isaacschlueter', - 'hostname': 'jabber.org' - }, - - 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar' : { - 'href' : 'http://atpass:foo%40bar@127.0.0.1:8080/path?search=foo#bar', - 'protocol' : 'http:', - 'slashes': true, - 'host' : '127.0.0.1:8080', - 'auth' : 'atpass:foo@bar', - 'hostname' : '127.0.0.1', - 'port' : '8080', - 'pathname': '/path', - 'search' : '?search=foo', - 'query' : 'search=foo', - 'hash' : '#bar', - 'path': '/path?search=foo' - }, - - 'svn+ssh://foo/bar': { - 'href': 'svn+ssh://foo/bar', - 'host': 'foo', - 'hostname': 'foo', - 'protocol': 'svn+ssh:', - 'pathname': '/bar', - 'path': '/bar', - 'slashes': true - }, - - 'dash-test://foo/bar': { - 'href': 'dash-test://foo/bar', - 'host': 'foo', - 'hostname': 'foo', - 'protocol': 'dash-test:', - 'pathname': '/bar', - 'path': '/bar', - 'slashes': true - }, - - 'dash-test:foo/bar': { - 'href': 'dash-test:foo/bar', - 'host': 'foo', - 'hostname': 'foo', - 'protocol': 'dash-test:', - 'pathname': '/bar', - 'path': '/bar' - }, - - 'dot.test://foo/bar': { - 'href': 'dot.test://foo/bar', - 'host': 'foo', - 'hostname': 'foo', - 'protocol': 'dot.test:', - 'pathname': '/bar', - 'path': '/bar', - 'slashes': true - }, - - 'dot.test:foo/bar': { - 'href': 'dot.test:foo/bar', - 'host': 'foo', - 'hostname': 'foo', - 'protocol': 'dot.test:', - 'pathname': '/bar', - 'path': '/bar' - }, - - // IDNA tests - 'http://www.日本語.com/' : { - 'href': 'http://www.xn--wgv71a119e.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.xn--wgv71a119e.com', - 'hostname': 'www.xn--wgv71a119e.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://example.Bücher.com/' : { - 'href': 'http://example.xn--bcher-kva.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.xn--bcher-kva.com', - 'hostname': 'example.xn--bcher-kva.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://www.Äffchen.com/' : { - 'href': 'http://www.xn--ffchen-9ta.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.xn--ffchen-9ta.com', - 'hostname': 'www.xn--ffchen-9ta.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://www.Äffchen.cOm;A/b/c?d=e#f gi' : { - 'href': 'http://www.xn--ffchen-9ta.com/;A/b/c?d=e#f%20g%3Ch%3Ei', - 'protocol': 'http:', - 'slashes': true, - 'host': 'www.xn--ffchen-9ta.com', - 'hostname': 'www.xn--ffchen-9ta.com', - 'pathname': ';A/b/c', - 'search': '?d=e', - 'query': 'd=e', - 'hash': '#f%20g%3Ch%3Ei', - 'path': ';A/b/c?d=e' - }, - - 'http://SÉLIER.COM/' : { - 'href': 'http://xn--slier-bsa.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'xn--slier-bsa.com', - 'hostname': 'xn--slier-bsa.com', - 'pathname': '/', - 'path': '/' - }, - - 'http://ليهمابتكلموشعربي؟.ي؟/' : { - 'href': 'http://xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', - 'hostname': 'xn--egbpdaj6bu4bxfgehfvwxn.xn--egb9f', - 'pathname': '/', - 'path': '/' - }, - - 'http://➡.ws/➡' : { - 'href': 'http://xn--hgi.ws/➡', - 'protocol': 'http:', - 'slashes': true, - 'host': 'xn--hgi.ws', - 'hostname': 'xn--hgi.ws', - 'pathname': '/➡', - 'path': '/➡' - }, - - 'http://bucket_name.s3.amazonaws.com/image.jpg': { - protocol: 'http:', - 'slashes': true, - slashes: true, - host: 'bucket_name.s3.amazonaws.com', - hostname: 'bucket_name.s3.amazonaws.com', - pathname: '/image.jpg', - href: 'http://bucket_name.s3.amazonaws.com/image.jpg', - 'path': '/image.jpg' - }, - - 'git+http://github.com/joyent/node.git': { - protocol: 'git+http:', - slashes: true, - host: 'github.com', - hostname: 'github.com', - pathname: '/joyent/node.git', - path: '/joyent/node.git', - href: 'git+http://github.com/joyent/node.git' - }, - - //if local1@domain1 is uses as a relative URL it may - //be parse into auth@hostname, but here there is no - //way to make it work in url.parse, I add the test to be explicit - 'local1@domain1': { - 'pathname': 'local1@domain1', - 'path': 'local1@domain1', - 'href': 'local1@domain1' - }, - - //While this may seem counter-intuitive, a browser will parse - // as a path. - 'www.example.com' : { - 'href': 'www.example.com', - 'pathname': 'www.example.com', - 'path': 'www.example.com' - }, - - // ipv6 support - '[fe80::1]': { - 'href': '[fe80::1]', - 'pathname': '[fe80::1]', - 'path': '[fe80::1]' - }, - - 'coap://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]': { - 'protocol': 'coap:', - 'slashes': true, - 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]', - 'hostname': 'fedc:ba98:7654:3210:fedc:ba98:7654:3210', - 'href': 'coap://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]/', - 'pathname': '/', - 'path': '/' - }, - - 'coap://[1080:0:0:0:8:800:200C:417A]:61616/': { - 'protocol': 'coap:', - 'slashes': true, - 'host': '[1080:0:0:0:8:800:200c:417a]:61616', - 'port': '61616', - 'hostname': '1080:0:0:0:8:800:200c:417a', - 'href': 'coap://[1080:0:0:0:8:800:200c:417a]:61616/', - 'pathname': '/', - 'path': '/' - }, - - 'http://user:password@[3ffe:2a00:100:7031::1]:8080': { - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:password', - 'host': '[3ffe:2a00:100:7031::1]:8080', - 'port': '8080', - 'hostname': '3ffe:2a00:100:7031::1', - 'href': 'http://user:password@[3ffe:2a00:100:7031::1]:8080/', - 'pathname': '/', - 'path': '/' - }, - - 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature': { - 'protocol': 'coap:', - 'slashes': true, - 'auth': 'u:p', - 'host': '[::192.9.5.5]:61616', - 'port': '61616', - 'hostname': '::192.9.5.5', - 'href': 'coap://u:p@[::192.9.5.5]:61616/.well-known/r?n=Temperature', - 'search': '?n=Temperature', - 'query': 'n=Temperature', - 'pathname': '/.well-known/r', - 'path': '/.well-known/r?n=Temperature' - }, - - // empty port - 'http://example.com:': { - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com', - 'hostname': 'example.com', - 'href': 'http://example.com/', - 'pathname': '/', - 'path': '/' - }, - - 'http://example.com:/a/b.html': { - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com', - 'hostname': 'example.com', - 'href': 'http://example.com/a/b.html', - 'pathname': '/a/b.html', - 'path': '/a/b.html' - }, - - 'http://example.com:?a=b': { - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com', - 'hostname': 'example.com', - 'href': 'http://example.com/?a=b', - 'search': '?a=b', - 'query': 'a=b', - 'pathname': '/', - 'path': '/?a=b' - }, - - 'http://example.com:#abc': { - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com', - 'hostname': 'example.com', - 'href': 'http://example.com/#abc', - 'hash': '#abc', - 'pathname': '/', - 'path': '/' - }, - - 'http://[fe80::1]:/a/b?a=b#abc': { - 'protocol': 'http:', - 'slashes': true, - 'host': '[fe80::1]', - 'hostname': 'fe80::1', - 'href': 'http://[fe80::1]/a/b?a=b#abc', - 'search': '?a=b', - 'query': 'a=b', - 'hash': '#abc', - 'pathname': '/a/b', - 'path': '/a/b?a=b' - }, - - 'http://-lovemonsterz.tumblr.com/rss': { - 'protocol': 'http:', - 'slashes': true, - 'host': '-lovemonsterz.tumblr.com', - 'hostname': '-lovemonsterz.tumblr.com', - 'href': 'http://-lovemonsterz.tumblr.com/rss', - 'pathname': '/rss', - 'path': '/rss', - }, - - 'http://-lovemonsterz.tumblr.com:80/rss': { - 'protocol': 'http:', - 'slashes': true, - 'port': '80', - 'host': '-lovemonsterz.tumblr.com:80', - 'hostname': '-lovemonsterz.tumblr.com', - 'href': 'http://-lovemonsterz.tumblr.com:80/rss', - 'pathname': '/rss', - 'path': '/rss', - }, - - 'http://user:pass@-lovemonsterz.tumblr.com/rss': { - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:pass', - 'host': '-lovemonsterz.tumblr.com', - 'hostname': '-lovemonsterz.tumblr.com', - 'href': 'http://user:pass@-lovemonsterz.tumblr.com/rss', - 'pathname': '/rss', - 'path': '/rss', - }, - - 'http://user:pass@-lovemonsterz.tumblr.com:80/rss': { - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:pass', - 'port': '80', - 'host': '-lovemonsterz.tumblr.com:80', - 'hostname': '-lovemonsterz.tumblr.com', - 'href': 'http://user:pass@-lovemonsterz.tumblr.com:80/rss', - 'pathname': '/rss', - 'path': '/rss', - }, - - 'http://_jabber._tcp.google.com/test': { - 'protocol': 'http:', - 'slashes': true, - 'host': '_jabber._tcp.google.com', - 'hostname': '_jabber._tcp.google.com', - 'href': 'http://_jabber._tcp.google.com/test', - 'pathname': '/test', - 'path': '/test', - }, - - 'http://user:pass@_jabber._tcp.google.com/test': { - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:pass', - 'host': '_jabber._tcp.google.com', - 'hostname': '_jabber._tcp.google.com', - 'href': 'http://user:pass@_jabber._tcp.google.com/test', - 'pathname': '/test', - 'path': '/test', - }, - - 'http://_jabber._tcp.google.com:80/test': { - 'protocol': 'http:', - 'slashes': true, - 'port': '80', - 'host': '_jabber._tcp.google.com:80', - 'hostname': '_jabber._tcp.google.com', - 'href': 'http://_jabber._tcp.google.com:80/test', - 'pathname': '/test', - 'path': '/test', - }, - - 'http://user:pass@_jabber._tcp.google.com:80/test': { - 'protocol': 'http:', - 'slashes': true, - 'auth': 'user:pass', - 'port': '80', - 'host': '_jabber._tcp.google.com:80', - 'hostname': '_jabber._tcp.google.com', - 'href': 'http://user:pass@_jabber._tcp.google.com:80/test', - 'pathname': '/test', - 'path': '/test', - }, - - 'http://x:1/\' <>"`/{}|\\^~`/': { - protocol: 'http:', - slashes: true, - host: 'x:1', - port: '1', - hostname: 'x', - pathname: '/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/', - path: '/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/', - href: 'http://x:1/%27%20%3C%3E%22%60/%7B%7D%7C/%5E~%60/' - }, - - 'http://a@b@c/': { - protocol: 'http:', - slashes: true, - auth: 'a@b', - host: 'c', - hostname: 'c', - href: 'http://a%40b@c/', - path: '/', - pathname: '/' - }, - - 'http://a@b?@c': { - protocol: 'http:', - slashes: true, - auth: 'a', - host: 'b', - hostname: 'b', - href: 'http://a@b/?@c', - path: '/?@c', - pathname: '/', - search: '?@c', - query: '@c' - }, - - 'http://a\r" \t\n<\'b:b@c\r\nd/e?f':{ - protocol: 'http:', - slashes: true, - auth: 'a\r" \t\n<\'b:b', - host: 'c', - port: null, - hostname: 'c', - hash: null, - search: '?f', - query: 'f', - pathname: '%0D%0Ad/e', - path: '%0D%0Ad/e?f', - href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f' - } - -}; - -for (var u in parseTests) { - var actual = url.parse(u), - spaced = url.parse(' \t ' + u + '\n\t'); - expected = parseTests[u]; - - Object.keys(actual).forEach(function (i) { - if (expected[i] === undefined && actual[i] === null) { - expected[i] = null; - } - }); - - assert.deepEqual(actual, expected); - assert.deepEqual(spaced, expected); - - var expected = parseTests[u].href, - actual = url.format(parseTests[u]); - - assert.equal(actual, expected, - 'format(' + u + ') == ' + u + '\nactual:' + actual); -} - -var parseTestsWithQueryString = { - '/foo/bar?baz=quux#frag' : { - 'href': '/foo/bar?baz=quux#frag', - 'hash': '#frag', - 'search': '?baz=quux', - 'query': { - 'baz': 'quux' - }, - 'pathname': '/foo/bar', - 'path': '/foo/bar?baz=quux' - }, - 'http://example.com' : { - 'href': 'http://example.com/', - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com', - 'hostname': 'example.com', - 'query': {}, - 'search': '', - 'pathname': '/', - 'path': '/' - }, - '/example': { - protocol: null, - slashes: null, - auth: null, - host: null, - port: null, - hostname: null, - hash: null, - search: '', - query: {}, - pathname: '/example', - path: '/example', - href: '/example' - }, - '/example?query=value':{ - protocol: null, - slashes: null, - auth: null, - host: null, - port: null, - hostname: null, - hash: null, - search: '?query=value', - query: { query: 'value' }, - pathname: '/example', - path: '/example?query=value', - href: '/example?query=value' - } -}; -for (var u in parseTestsWithQueryString) { - var actual = url.parse(u, true); - var expected = parseTestsWithQueryString[u]; - for (var i in actual) { - if (actual[i] === null && expected[i] === undefined) { - expected[i] = null; - } - } - - assert.deepEqual(actual, expected); -} - -// some extra formatting tests, just to verify -// that it'll format slightly wonky content to a valid url. -var formatTests = { - 'http://example.com?' : { - 'href': 'http://example.com/?', - 'protocol': 'http:', - 'slashes': true, - 'host': 'example.com', - 'hostname': 'example.com', - 'search': '?', - 'query': {}, - 'pathname': '/' - }, - 'http://example.com?foo=bar#frag' : { - 'href': 'http://example.com/?foo=bar#frag', - 'protocol': 'http:', - 'host': 'example.com', - 'hostname': 'example.com', - 'hash': '#frag', - 'search': '?foo=bar', - 'query': 'foo=bar', - 'pathname': '/' - }, - 'http://example.com?foo=@bar#frag' : { - 'href': 'http://example.com/?foo=@bar#frag', - 'protocol': 'http:', - 'host': 'example.com', - 'hostname': 'example.com', - 'hash': '#frag', - 'search': '?foo=@bar', - 'query': 'foo=@bar', - 'pathname': '/' - }, - 'http://example.com?foo=/bar/#frag' : { - 'href': 'http://example.com/?foo=/bar/#frag', - 'protocol': 'http:', - 'host': 'example.com', - 'hostname': 'example.com', - 'hash': '#frag', - 'search': '?foo=/bar/', - 'query': 'foo=/bar/', - 'pathname': '/' - }, - 'http://example.com?foo=?bar/#frag' : { - 'href': 'http://example.com/?foo=?bar/#frag', - 'protocol': 'http:', - 'host': 'example.com', - 'hostname': 'example.com', - 'hash': '#frag', - 'search': '?foo=?bar/', - 'query': 'foo=?bar/', - 'pathname': '/' - }, - 'http://example.com#frag=?bar/#frag' : { - 'href': 'http://example.com/#frag=?bar/#frag', - 'protocol': 'http:', - 'host': 'example.com', - 'hostname': 'example.com', - 'hash': '#frag=?bar/#frag', - 'pathname': '/' - }, - 'http://google.com" onload="alert(42)/' : { - 'href': 'http://google.com/%22%20onload=%22alert(42)/', - 'protocol': 'http:', - 'host': 'google.com', - 'pathname': '/%22%20onload=%22alert(42)/' - }, - 'http://a.com/a/b/c?s#h' : { - 'href': 'http://a.com/a/b/c?s#h', - 'protocol': 'http', - 'host': 'a.com', - 'pathname': 'a/b/c', - 'hash': 'h', - 'search': 's' - }, - 'xmpp:isaacschlueter@jabber.org' : { - 'href': 'xmpp:isaacschlueter@jabber.org', - 'protocol': 'xmpp:', - 'host': 'jabber.org', - 'auth': 'isaacschlueter', - 'hostname': 'jabber.org' - }, - 'http://atpass:foo%40bar@127.0.0.1/' : { - 'href': 'http://atpass:foo%40bar@127.0.0.1/', - 'auth': 'atpass:foo@bar', - 'hostname': '127.0.0.1', - 'protocol': 'http:', - 'pathname': '/' - }, - 'http://atslash%2F%40:%2F%40@foo/' : { - 'href': 'http://atslash%2F%40:%2F%40@foo/', - 'auth': 'atslash/@:/@', - 'hostname': 'foo', - 'protocol': 'http:', - 'pathname': '/' - }, - 'svn+ssh://foo/bar': { - 'href': 'svn+ssh://foo/bar', - 'hostname': 'foo', - 'protocol': 'svn+ssh:', - 'pathname': '/bar', - 'slashes': true - }, - 'dash-test://foo/bar': { - 'href': 'dash-test://foo/bar', - 'hostname': 'foo', - 'protocol': 'dash-test:', - 'pathname': '/bar', - 'slashes': true - }, - 'dash-test:foo/bar': { - 'href': 'dash-test:foo/bar', - 'hostname': 'foo', - 'protocol': 'dash-test:', - 'pathname': '/bar' - }, - 'dot.test://foo/bar': { - 'href': 'dot.test://foo/bar', - 'hostname': 'foo', - 'protocol': 'dot.test:', - 'pathname': '/bar', - 'slashes': true - }, - 'dot.test:foo/bar': { - 'href': 'dot.test:foo/bar', - 'hostname': 'foo', - 'protocol': 'dot.test:', - 'pathname': '/bar' - }, - // ipv6 support - 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature': { - 'href': 'coap:u:p@[::1]:61616/.well-known/r?n=Temperature', - 'protocol': 'coap:', - 'auth': 'u:p', - 'hostname': '::1', - 'port': '61616', - 'pathname': '/.well-known/r', - 'search': 'n=Temperature' - }, - 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton': { - 'href': 'coap:[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616/s/stopButton', - 'protocol': 'coap', - 'host': '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616', - 'pathname': '/s/stopButton' - }, - - // encode context-specific delimiters in path and query, but do not touch - // other non-delimiter chars like `%`. - // - - // `#`,`?` in path - '/path/to/%%23%3F+=&.txt?foo=theA1#bar' : { - href: '/path/to/%%23%3F+=&.txt?foo=theA1#bar', - pathname: '/path/to/%#?+=&.txt', - query: { - foo: 'theA1' - }, - hash: "#bar" - }, - - // `#`,`?` in path + `#` in query - '/path/to/%%23%3F+=&.txt?foo=the%231#bar' : { - href: '/path/to/%%23%3F+=&.txt?foo=the%231#bar', - pathname: '/path/to/%#?+=&.txt', - query: { - foo: 'the#1' - }, - hash: "#bar" - }, - - // `?` and `#` in path and search - 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag': { - href: 'http://ex.com/foo%3F100%m%23r?abc=the%231?&foo=bar#frag', - protocol: 'http:', - hostname: 'ex.com', - hash: '#frag', - search: '?abc=the#1?&foo=bar', - pathname: '/foo?100%m#r' - }, - - // `?` and `#` in search only - 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag': { - href: 'http://ex.com/fooA100%mBr?abc=the%231?&foo=bar#frag', - protocol: 'http:', - hostname: 'ex.com', - hash: '#frag', - search: '?abc=the#1?&foo=bar', - pathname: '/fooA100%mBr' - }, - - // path - 'http://github.com/joyent/node#js1': { - href: 'http://github.com/joyent/node#js1', - protocol: 'http:', - hostname: 'github.com', - hash: '#js1', - path: '/joyent/node' - }, - - // pathname vs. path, path wins - 'http://github.com/joyent/node2#js1': { - href: 'http://github.com/joyent/node2#js1', - protocol: 'http:', - hostname: 'github.com', - hash: '#js1', - path: '/joyent/node2', - pathname: '/joyent/node' - }, - - // pathname with query/search - 'http://github.com/joyent/node?foo=bar#js2': { - href: 'http://github.com/joyent/node?foo=bar#js2', - protocol: 'http:', - hostname: 'github.com', - hash: '#js2', - path: '/joyent/node?foo=bar' - }, - - // path vs. query, path wins - 'http://github.com/joyent/node?foo=bar2#js3': { - href: 'http://github.com/joyent/node?foo=bar2#js3', - protocol: 'http:', - hostname: 'github.com', - hash: '#js3', - path: '/joyent/node?foo=bar2', - query: {foo: 'bar'} - }, - - // path vs. search, path wins - 'http://github.com/joyent/node?foo=bar3#js4': { - href: 'http://github.com/joyent/node?foo=bar3#js4', - protocol: 'http:', - hostname: 'github.com', - hash: '#js4', - path: '/joyent/node?foo=bar3', - search: '?foo=bar' - }, - - // path is present without ? vs. query given - 'http://github.com/joyent/node#js5': { - href: 'http://github.com/joyent/node#js5', - protocol: 'http:', - hostname: 'github.com', - hash: '#js5', - path: '/joyent/node', - query: {foo: 'bar'} - }, - - // path is present without ? vs. search given - 'http://github.com/joyent/node#js6': { - href: 'http://github.com/joyent/node#js6', - protocol: 'http:', - hostname: 'github.com', - hash: '#js6', - path: '/joyent/node', - search: '?foo=bar' - } - -}; -for (var u in formatTests) { - var expect = formatTests[u].href; - delete formatTests[u].href; - var actual = url.format(u); - var actualObj = url.format(formatTests[u]); - assert.equal(actual, expect, - 'wonky format(' + u + ') == ' + expect + - '\nactual:' + actual); - assert.equal(actualObj, expect, - 'wonky format(' + JSON.stringify(formatTests[u]) + - ') == ' + expect + - '\nactual: ' + actualObj); -} - -/* - [from, path, expected] -*/ -var relativeTests = [ - ['/foo/bar/baz', 'quux', '/foo/bar/quux'], - ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'], - ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'], - ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'], - ['/foo/bar/baz', '/bar', '/bar'], - ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'], - ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'], - ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'], - ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'], - ['foo/bar', '../../../baz', '../../baz'], - ['foo/bar/', '../../../baz', '../baz'], - ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], - ['http://example.com/b//c//d;p?q#blarg', - 'https:/p/a/t/h?s#hash2', - 'https://p/a/t/h?s#hash2'], - ['http://example.com/b//c//d;p?q#blarg', - 'https://u:p@h.com/p/a/t/h?s#hash2', - 'https://u:p@h.com/p/a/t/h?s#hash2'], - ['http://example.com/b//c//d;p?q#blarg', - 'https:/a/b/c/d', - 'https://a/b/c/d'], - ['http://example.com/b//c//d;p?q#blarg', - 'http:#hash2', - 'http://example.com/b//c//d;p?q#hash2'], - ['http://example.com/b//c//d;p?q#blarg', - 'http:/p/a/t/h?s#hash2', - 'http://example.com/p/a/t/h?s#hash2'], - ['http://example.com/b//c//d;p?q#blarg', - 'http://u:p@h.com/p/a/t/h?s#hash2', - 'http://u:p@h.com/p/a/t/h?s#hash2'], - ['http://example.com/b//c//d;p?q#blarg', - 'http:/a/b/c/d', - 'http://example.com/a/b/c/d'], - ['/foo/bar/baz', '/../etc/passwd', '/etc/passwd'] -]; -relativeTests.forEach(function(relativeTest) { - var a = url.resolve(relativeTest[0], relativeTest[1]), - e = relativeTest[2]; - assert.equal(a, e, - 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e + - '\n actual=' + a); -}); - - -// https://github.com/joyent/node/issues/568 -[ - undefined, - null, - true, - false, - 0.0, - 0, - [], - {} -].forEach(function(val) { - assert.throws(function() { url.parse(val); }, TypeError); -}); - - -// -// Tests below taken from Chiron -// http://code.google.com/p/chironjs/source/browse/trunk/src/test/http/url.js -// -// Copyright (c) 2002-2008 Kris Kowal -// used with permission under MIT License -// -// Changes marked with @isaacs - -var bases = [ - 'http://a/b/c/d;p?q', - 'http://a/b/c/d;p?q=1/2', - 'http://a/b/c/d;p=1/2?q', - 'fred:///s//a/b/c', - 'http:///s//a/b/c' -]; - -//[to, from, result] -var relativeTests2 = [ - // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html - ['../c', 'foo:a/b', 'foo:c'], - ['foo:.', 'foo:a', 'foo:'], - ['/foo/../../../bar', 'zz:abc', 'zz:/bar'], - ['/foo/../bar', 'zz:abc', 'zz:/bar'], - // @isaacs Disagree. Not how web browsers resolve this. - ['foo/../../../bar', 'zz:abc', 'zz:bar'], - // ['foo/../../../bar', 'zz:abc', 'zz:../../bar'], // @isaacs Added - ['foo/../bar', 'zz:abc', 'zz:bar'], - ['zz:.', 'zz:abc', 'zz:'], - ['/.', bases[0], 'http://a/'], - ['/.foo', bases[0], 'http://a/.foo'], - ['.foo', bases[0], 'http://a/b/c/.foo'], - - // http://gbiv.com/protocols/uri/test/rel_examples1.html - // examples from RFC 2396 - ['g:h', bases[0], 'g:h'], - ['g', bases[0], 'http://a/b/c/g'], - ['./g', bases[0], 'http://a/b/c/g'], - ['g/', bases[0], 'http://a/b/c/g/'], - ['/g', bases[0], 'http://a/g'], - ['//g', bases[0], 'http://g/'], - // changed with RFC 2396bis - //('?y', bases[0], 'http://a/b/c/d;p?y'], - ['?y', bases[0], 'http://a/b/c/d;p?y'], - ['g?y', bases[0], 'http://a/b/c/g?y'], - // changed with RFC 2396bis - //('#s', bases[0], CURRENT_DOC_URI + '#s'], - ['#s', bases[0], 'http://a/b/c/d;p?q#s'], - ['g#s', bases[0], 'http://a/b/c/g#s'], - ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], - [';x', bases[0], 'http://a/b/c/;x'], - ['g;x', bases[0], 'http://a/b/c/g;x'], - ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], - // changed with RFC 2396bis - //('', bases[0], CURRENT_DOC_URI], - ['', bases[0], 'http://a/b/c/d;p?q'], - ['.', bases[0], 'http://a/b/c/'], - ['./', bases[0], 'http://a/b/c/'], - ['..', bases[0], 'http://a/b/'], - ['../', bases[0], 'http://a/b/'], - ['../g', bases[0], 'http://a/b/g'], - ['../..', bases[0], 'http://a/'], - ['../../', bases[0], 'http://a/'], - ['../../g' , bases[0], 'http://a/g'], - ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], - ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], - // changed with RFC 2396bis - //('/./g', bases[0], 'http://a/./g'], - ['/./g', bases[0], 'http://a/g'], - // changed with RFC 2396bis - //('/../g', bases[0], 'http://a/../g'], - ['/../g', bases[0], 'http://a/g'], - ['g.', bases[0], 'http://a/b/c/g.'], - ['.g', bases[0], 'http://a/b/c/.g'], - ['g..', bases[0], 'http://a/b/c/g..'], - ['..g', bases[0], 'http://a/b/c/..g'], - ['./../g', bases[0], 'http://a/b/g'], - ['./g/.', bases[0], 'http://a/b/c/g/'], - ['g/./h', bases[0], 'http://a/b/c/g/h'], - ['g/../h', bases[0], 'http://a/b/c/h'], - ['g;x=1/./y', bases[0], 'http://a/b/c/g;x=1/y'], - ['g;x=1/../y', bases[0], 'http://a/b/c/y'], - ['g?y/./x', bases[0], 'http://a/b/c/g?y/./x'], - ['g?y/../x', bases[0], 'http://a/b/c/g?y/../x'], - ['g#s/./x', bases[0], 'http://a/b/c/g#s/./x'], - ['g#s/../x', bases[0], 'http://a/b/c/g#s/../x'], - ['http:g', bases[0], ('http:g', 'http://a/b/c/g')], - ['http:', bases[0], ('http:', bases[0])], - // not sure where this one originated - ['/a/b/c/./../../g', bases[0], 'http://a/a/g'], - - // http://gbiv.com/protocols/uri/test/rel_examples2.html - // slashes in base URI's query args - ['g', bases[1], 'http://a/b/c/g'], - ['./g', bases[1], 'http://a/b/c/g'], - ['g/', bases[1], 'http://a/b/c/g/'], - ['/g', bases[1], 'http://a/g'], - ['//g', bases[1], 'http://g/'], - // changed in RFC 2396bis - //('?y', bases[1], 'http://a/b/c/?y'], - ['?y', bases[1], 'http://a/b/c/d;p?y'], - ['g?y', bases[1], 'http://a/b/c/g?y'], - ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], - ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], - ['g#s', bases[1], 'http://a/b/c/g#s'], - ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], - ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], - ['./', bases[1], 'http://a/b/c/'], - ['../', bases[1], 'http://a/b/'], - ['../g', bases[1], 'http://a/b/g'], - ['../../', bases[1], 'http://a/'], - ['../../g' , bases[1], 'http://a/g'], - - // http://gbiv.com/protocols/uri/test/rel_examples3.html - // slashes in path params - // all of these changed in RFC 2396bis - ['g', bases[2], 'http://a/b/c/d;p=1/g'], - ['./g', bases[2], 'http://a/b/c/d;p=1/g'], - ['g/', bases[2], 'http://a/b/c/d;p=1/g/'], - ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'], - [';x', bases[2], 'http://a/b/c/d;p=1/;x'], - ['g;x', bases[2], 'http://a/b/c/d;p=1/g;x'], - ['g;x=1/./y', bases[2], 'http://a/b/c/d;p=1/g;x=1/y'], - ['g;x=1/../y', bases[2], 'http://a/b/c/d;p=1/y'], - ['./', bases[2], 'http://a/b/c/d;p=1/'], - ['../', bases[2], 'http://a/b/c/'], - ['../g', bases[2], 'http://a/b/c/g'], - ['../../', bases[2], 'http://a/b/'], - ['../../g' , bases[2], 'http://a/b/g'], - - // http://gbiv.com/protocols/uri/test/rel_examples4.html - // double and triple slash, unknown scheme - ['g:h', bases[3], 'g:h'], - ['g', bases[3], 'fred:///s//a/b/g'], - ['./g', bases[3], 'fred:///s//a/b/g'], - ['g/', bases[3], 'fred:///s//a/b/g/'], - ['/g', bases[3], 'fred:///g'], // may change to fred:///s//a/g - ['//g', bases[3], 'fred://g'], // may change to fred:///s//g - ['//g/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x - ['///g', bases[3], 'fred:///g'], - ['./', bases[3], 'fred:///s//a/b/'], - ['../', bases[3], 'fred:///s//a/'], - ['../g', bases[3], 'fred:///s//a/g'], - - ['../../', bases[3], 'fred:///s//'], - ['../../g' , bases[3], 'fred:///s//g'], - ['../../../g', bases[3], 'fred:///s/g'], - // may change to fred:///s//a/../../../g - ['../../../../g', bases[3], 'fred:///g'], - - // http://gbiv.com/protocols/uri/test/rel_examples5.html - // double and triple slash, well-known scheme - ['g:h', bases[4], 'g:h'], - ['g', bases[4], 'http:///s//a/b/g'], - ['./g', bases[4], 'http:///s//a/b/g'], - ['g/', bases[4], 'http:///s//a/b/g/'], - ['/g', bases[4], 'http:///g'], // may change to http:///s//a/g - ['//g', bases[4], 'http://g/'], // may change to http:///s//g - ['//g/x', bases[4], 'http://g/x'], // may change to http:///s//g/x - ['///g', bases[4], 'http:///g'], - ['./', bases[4], 'http:///s//a/b/'], - ['../', bases[4], 'http:///s//a/'], - ['../g', bases[4], 'http:///s//a/g'], - ['../../', bases[4], 'http:///s//'], - ['../../g' , bases[4], 'http:///s//g'], - // may change to http:///s//a/../../g - ['../../../g', bases[4], 'http:///s/g'], - // may change to http:///s//a/../../../g - ['../../../../g', bases[4], 'http:///g'], - - // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py - ['bar:abc', 'foo:xyz', 'bar:abc'], - ['../abc', 'http://example/x/y/z', 'http://example/x/abc'], - ['http://example/x/abc', 'http://example2/x/y/z', 'http://example/x/abc'], - ['../r', 'http://ex/x/y/z', 'http://ex/x/r'], - ['q/r', 'http://ex/x/y', 'http://ex/x/q/r'], - ['q/r#s', 'http://ex/x/y', 'http://ex/x/q/r#s'], - ['q/r#s/t', 'http://ex/x/y', 'http://ex/x/q/r#s/t'], - ['ftp://ex/x/q/r', 'http://ex/x/y', 'ftp://ex/x/q/r'], - ['', 'http://ex/x/y', 'http://ex/x/y'], - ['', 'http://ex/x/y/', 'http://ex/x/y/'], - ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'], - ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], - ['#Animal', - 'file:/swap/test/animal.rdf', - 'file:/swap/test/animal.rdf#Animal'], - ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], - ['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/x/abc'], - ['../r', 'file:/ex/x/y/z', 'file:/ex/x/r'], - ['/r', 'file:/ex/x/y/z', 'file:/r'], - ['q/r', 'file:/ex/x/y', 'file:/ex/x/q/r'], - ['q/r#s', 'file:/ex/x/y', 'file:/ex/x/q/r#s'], - ['q/r#', 'file:/ex/x/y', 'file:/ex/x/q/r#'], - ['q/r#s/t', 'file:/ex/x/y', 'file:/ex/x/q/r#s/t'], - ['ftp://ex/x/q/r', 'file:/ex/x/y', 'ftp://ex/x/q/r'], - ['', 'file:/ex/x/y', 'file:/ex/x/y'], - ['', 'file:/ex/x/y/', 'file:/ex/x/y/'], - ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'], - ['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], - ['file://meetings.example.com/cal#m1', - 'file:/devel/WWW/2000/10/swap/test/reluri-1.n3', - 'file://meetings.example.com/cal#m1'], - ['file://meetings.example.com/cal#m1', - 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', - 'file://meetings.example.com/cal#m1'], - ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'], - ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], - // Ryan Lee - ['./', 'http://example/x/abc.efg', 'http://example/x/'], - - - // Graham Klyne's tests - // http://www.ninebynine.org/Software/HaskellUtils/Network/UriTest.xls - // 01-31 are from Connelly's cases - - // 32-49 - ['./q:r', 'http://ex/x/y', 'http://ex/x/q:r'], - ['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=q:r'], - ['?pp/rr', 'http://ex/x/y?pp/qq', 'http://ex/x/y?pp/rr'], - ['y/z', 'http://ex/x/y?pp/qq', 'http://ex/x/y/z'], - ['local/qual@domain.org#frag', - 'mailto:local', - 'mailto:local/qual@domain.org#frag'], - ['more/qual2@domain2.org#frag', - 'mailto:local/qual1@domain1.org', - 'mailto:local/more/qual2@domain2.org#frag'], - ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'], - ['/x/y?q', 'http://ex?p', 'http://ex/x/y?q'], - ['c/d', 'foo:a/b', 'foo:a/c/d'], - ['/c/d', 'foo:a/b', 'foo:/c/d'], - ['', 'foo:a/b?c#d', 'foo:a/b?c'], - ['b/c', 'foo:a', 'foo:b/c'], - ['../b/c', 'foo:/a/y/z', 'foo:/a/b/c'], - ['./b/c', 'foo:a', 'foo:b/c'], - ['/./b/c', 'foo:a', 'foo:/b/c'], - ['../../d', 'foo://a//b/c', 'foo://a/d'], - ['.', 'foo:a', 'foo:'], - ['..', 'foo:a', 'foo:'], - - // 50-57[cf. TimBL comments -- - // http://lists.w3.org/Archives/Public/uri/2003Feb/0028.html, - // http://lists.w3.org/Archives/Public/uri/2003Jan/0008.html) - ['abc', 'http://example/x/y%2Fz', 'http://example/x/abc'], - ['../../x%2Fabc', 'http://example/a/x/y/z', 'http://example/a/x%2Fabc'], - ['../x%2Fabc', 'http://example/a/x/y%2Fz', 'http://example/a/x%2Fabc'], - ['abc', 'http://example/x%2Fy/z', 'http://example/x%2Fy/abc'], - ['q%3Ar', 'http://ex/x/y', 'http://ex/x/q%3Ar'], - ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], - ['/x%2Fabc', 'http://example/x/y/z', 'http://example/x%2Fabc'], - ['/x%2Fabc', 'http://example/x/y%2Fz', 'http://example/x%2Fabc'], - - // 70-77 - ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], - ['local2@domain2?query2', - 'mailto:local1@domain1', - 'mailto:local2@domain2?query2'], - ['local2@domain2?query2', - 'mailto:local1@domain1?query1', - 'mailto:local2@domain2?query2'], - ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], - ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], - ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], - ['http://example/a/b?c/../d', 'foo:bar', 'http://example/a/b?c/../d'], - ['http://example/a/b#c/../d', 'foo:bar', 'http://example/a/b#c/../d'], - - // 82-88 - // @isaacs Disagree. Not how browsers do it. - // ['http:this', 'http://example.org/base/uri', 'http:this'], - // @isaacs Added - ['http:this', 'http://example.org/base/uri', 'http://example.org/base/this'], - ['http:this', 'http:base', 'http:this'], - ['.//g', 'f:/a', 'f://g'], - ['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], - ['m2@example.ord/c2@example.org', - 'mid:m@example.ord/c@example.org', - 'mid:m@example.ord/m2@example.ord/c2@example.org'], - ['mini1.xml', - 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/', - 'file:///C:/DEV/Haskell/lib/HXmlToolbox-3.01/examples/mini1.xml'], - ['../b/c', 'foo:a/y/z', 'foo:a/b/c'], - - //changeing auth - ['http://diff:auth@www.example.com', - 'http://asdf:qwer@www.example.com', - 'http://diff:auth@www.example.com/'] -]; -relativeTests2.forEach(function(relativeTest) { - var a = url.resolve(relativeTest[1], relativeTest[0]), - e = relativeTest[2]; - assert.equal(a, e, - 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e + - '\n actual=' + a); -}); - -//if format and parse are inverse operations then -//resolveObject(parse(x), y) == parse(resolve(x, y)) - -//host and hostname are special, in this case a '' value is important -var emptyIsImportant = {'host': true, 'hostname': ''}; - -//format: [from, path, expected] -relativeTests.forEach(function(relativeTest) { - var actual = url.resolveObject(url.parse(relativeTest[0]), relativeTest[1]), - expected = url.parse(relativeTest[2]); - - - assert.deepEqual(actual, expected); - - expected = relativeTest[2]; - actual = url.format(actual); - - assert.equal(actual, expected, - 'format(' + actual + ') == ' + expected + '\nactual:' + actual); -}); - -//format: [to, from, result] -// the test: ['.//g', 'f:/a', 'f://g'] is a fundamental problem -// url.parse('f:/a') does not have a host -// url.resolve('f:/a', './/g') does not have a host because you have moved -// down to the g directory. i.e. f: //g, however when this url is parsed -// f:// will indicate that the host is g which is not the case. -// it is unclear to me how to keep this information from being lost -// it may be that a pathname of ////g should collapse to /g but this seems -// to be a lot of work for an edge case. Right now I remove the test -if (relativeTests2[181][0] === './/g' && - relativeTests2[181][1] === 'f:/a' && - relativeTests2[181][2] === 'f://g') { - relativeTests2.splice(181, 1); -} -relativeTests2.forEach(function(relativeTest) { - var actual = url.resolveObject(url.parse(relativeTest[1]), relativeTest[0]), - expected = url.parse(relativeTest[2]); - - assert.deepEqual(actual, expected); - - var expected = relativeTest[2], - actual = url.format(actual); - - assert.equal(actual, expected, - 'format(' + relativeTest[1] + ') == ' + expected + - '\nactual:' + actual); -}); diff --git a/test/simple/test-utf8-scripts.js b/test/simple/test-utf8-scripts.js deleted file mode 100644 index 4639304f8..000000000 --- a/test/simple/test-utf8-scripts.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -// üäö - -console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη'); - -assert.equal(true, /Hellö Wörld/.test('Hellö Wörld')); - diff --git a/test/simple/test-util-debug.js b/test/simple/test-util-debug.js deleted file mode 100644 index 6d9c28a95..000000000 --- a/test/simple/test-util-debug.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -if (process.argv[2] === 'child') - child(); -else - parent(); - -function parent() { - test('foo,tud,bar', true); - test('foo,tud', true); - test('tud,bar', true); - test('tud', true); - test('foo,bar', false); - test('', false); -} - -function test(environ, shouldWrite) { - var expectErr = ''; - if (shouldWrite) { - expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' + - 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; - } - var expectOut = 'ok\n'; - var didTest = false; - - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { - env: { NODE_DEBUG: environ } - }); - - expectErr = expectErr.split('%PID%').join(child.pid); - - var err = ''; - child.stderr.setEncoding('utf8'); - child.stderr.on('data', function(c) { - err += c; - }); - - var out = ''; - child.stdout.setEncoding('utf8'); - child.stdout.on('data', function(c) { - out += c; - }); - - child.on('close', function(c) { - assert(!c); - assert.equal(err, expectErr); - assert.equal(out, expectOut); - didTest = true; - console.log('ok %j %j', environ, shouldWrite); - }); - - process.on('exit', function() { - assert(didTest); - }); -} - - -function child() { - var util = require('util'); - var debug = util.debuglog('tud'); - debug('this', { is: 'a' }, /debugging/); - debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); - console.log('ok'); -} diff --git a/test/simple/test-util-format.js b/test/simple/test-util-format.js deleted file mode 100644 index 1bea1bf21..000000000 --- a/test/simple/test-util-format.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); - -assert.equal(util.format(), ''); -assert.equal(util.format(''), ''); -assert.equal(util.format([]), '[]'); -assert.equal(util.format({}), '{}'); -assert.equal(util.format(null), 'null'); -assert.equal(util.format(true), 'true'); -assert.equal(util.format(false), 'false'); -assert.equal(util.format('test'), 'test'); - -// CHECKME this is for console.log() compatibility - but is it *right*? -assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); - -assert.equal(util.format('%d', 42.0), '42'); -assert.equal(util.format('%d', 42), '42'); -assert.equal(util.format('%s', 42), '42'); -assert.equal(util.format('%j', 42), '42'); - -assert.equal(util.format('%d', '42.0'), '42'); -assert.equal(util.format('%d', '42'), '42'); -assert.equal(util.format('%s', '42'), '42'); -assert.equal(util.format('%j', '42'), '"42"'); - -assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); - -assert.equal(util.format('%s'), '%s'); -assert.equal(util.format('%s', undefined), 'undefined'); -assert.equal(util.format('%s', 'foo'), 'foo'); -assert.equal(util.format('%s:%s'), '%s:%s'); -assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); -assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); -assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); -assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); -assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); -assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); - -(function() { - var o = {}; - o.o = o; - assert.equal(util.format('%j', o), '[Circular]'); -})(); - -// Errors -assert.equal(util.format(new Error('foo')), '[Error: foo]'); -function CustomError(msg) { - Error.call(this); - Object.defineProperty(this, 'message', { value: msg, enumerable: false }); - Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); -} -util.inherits(CustomError, Error); -assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); diff --git a/test/simple/test-util-inspect.js b/test/simple/test-util-inspect.js deleted file mode 100644 index 2a7c2c4fc..000000000 --- a/test/simple/test-util-inspect.js +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); - -// test the internal isDate implementation -var Date2 = require('vm').runInNewContext('Date'); -var d = new Date2(); -var orig = util.inspect(d); -Date2.prototype.foo = 'bar'; -var after = util.inspect(d); -assert.equal(orig, after); - -// test positive/negative zero -assert.equal(util.inspect(0), '0'); -assert.equal(util.inspect(-0), '-0'); - -// test for sparse array -var a = ['foo', 'bar', 'baz']; -assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); -delete a[1]; -assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); -assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); -assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); - -// test for property descriptors -var getter = Object.create(null, { - a: { - get: function() { return 'aaa'; } - } -}); -var setter = Object.create(null, { - b: { - set: function() {} - } -}); -var getterAndSetter = Object.create(null, { - c: { - get: function() { return 'ccc'; }, - set: function() {} - } -}); -assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); -assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); -assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); - -// exceptions should print the error message, not '{}' -assert.equal(util.inspect(new Error()), '[Error]'); -assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); -assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); -assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); -try { - undef(); -} catch (e) { - assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); -} -var ex = util.inspect(new Error('FAIL'), true); -assert.ok(ex.indexOf('[Error: FAIL]') != -1); -assert.ok(ex.indexOf('[stack]') != -1); -assert.ok(ex.indexOf('[message]') != -1); - -// GH-1941 -// should not throw: -assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); - -// GH-1944 -assert.doesNotThrow(function() { - var d = new Date(); - d.toUTCString = null; - util.inspect(d); -}); - -assert.doesNotThrow(function() { - var r = /regexp/; - r.toString = null; - util.inspect(r); -}); - -// bug with user-supplied inspect function returns non-string -assert.doesNotThrow(function() { - util.inspect([{ - inspect: function() { return 123; } - }]); -}); - -// GH-2225 -var x = { inspect: util.inspect }; -assert.ok(util.inspect(x).indexOf('inspect') != -1); - -// util.inspect should not display the escaped value of a key. -var w = { - '\\': 1, - '\\\\': 2, - '\\\\\\': 3, - '\\\\\\\\': 4, -} - -var y = ['a', 'b', 'c']; -y['\\\\\\'] = 'd'; - -assert.ok(util.inspect(w), - '{ \'\\\': 1, \'\\\\\': 2, \'\\\\\\\': 3, \'\\\\\\\\\': 4 }'); -assert.ok(util.inspect(y), '[ \'a\', \'b\', \'c\', \'\\\\\\\': \'d\' ]'); - -// util.inspect.styles and util.inspect.colors -function test_color_style(style, input, implicit) { - var color_name = util.inspect.styles[style]; - var color = ['', '']; - if(util.inspect.colors[color_name]) - color = util.inspect.colors[color_name]; - - var without_color = util.inspect(input, false, 0, false); - var with_color = util.inspect(input, false, 0, true); - var expect = '\u001b[' + color[0] + 'm' + without_color + - '\u001b[' + color[1] + 'm'; - assert.equal(with_color, expect, 'util.inspect color for style '+style); -} - -test_color_style('special', function(){}); -test_color_style('number', 123.456); -test_color_style('boolean', true); -test_color_style('undefined', undefined); -test_color_style('null', null); -test_color_style('string', 'test string'); -test_color_style('date', new Date); -test_color_style('regexp', /regexp/); - -// an object with "hasOwnProperty" overwritten should not throw -assert.doesNotThrow(function() { - util.inspect({ - hasOwnProperty: null - }); -}); - -// new API, accepts an "options" object -var subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; -Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); - -assert(util.inspect(subject, { showHidden: false }).indexOf('hidden') === -1); -assert(util.inspect(subject, { showHidden: true }).indexOf('hidden') !== -1); -assert(util.inspect(subject, { colors: false }).indexOf('\u001b[32m') === -1); -assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1); -assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1); -assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1); -assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); - -// "customInspect" option can enable/disable calling inspect() on objects -subject = { inspect: function() { return 123; } }; - -assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); -assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); - -// custom inspect() functions should be able to return other Objects -subject.inspect = function() { return { foo: 'bar' }; }; - -assert.equal(util.inspect(subject), '{ foo: \'bar\' }'); - -subject.inspect = function(depth, opts) { - assert.strictEqual(opts.customInspectOptions, true); -}; - -util.inspect(subject, { customInspectOptions: true }); - -// util.inspect with "colors" option should produce as many lines as without it -function test_lines(input) { - var count_lines = function(str) { - return (str.match(/\n/g) || []).length; - } - - var without_color = util.inspect(input); - var with_color = util.inspect(input, {colors: true}); - assert.equal(count_lines(without_color), count_lines(with_color)); -} - -test_lines([1, 2, 3, 4, 5, 6, 7]); -test_lines(function() { - var big_array = []; - for (var i = 0; i < 100; i++) { - big_array.push(i); - } - return big_array; -}()); -test_lines({foo: 'bar', baz: 35, b: {a: 35}}); -test_lines({ - foo: 'bar', - baz: 35, - b: {a: 35}, - very_long_key: 'very_long_value', - even_longer_key: ['with even longer value in array'] -}); - -// test boxed primitives output the correct values -assert.equal(util.inspect(new String('test')), '[String: \'test\']'); -assert.equal(util.inspect(new Boolean(false)), '[Boolean: false]'); -assert.equal(util.inspect(new Boolean(true)), '[Boolean: true]'); -assert.equal(util.inspect(new Number(0)), '[Number: 0]'); -assert.equal(util.inspect(new Number(-0)), '[Number: -0]'); -assert.equal(util.inspect(new Number(-1.1)), '[Number: -1.1]'); -assert.equal(util.inspect(new Number(13.37)), '[Number: 13.37]'); - -// test boxed primitives with own properties -var str = new String('baz'); -str.foo = 'bar'; -assert.equal(util.inspect(str), '{ [String: \'baz\'] foo: \'bar\' }'); - -var bool = new Boolean(true); -bool.foo = 'bar'; -assert.equal(util.inspect(bool), '{ [Boolean: true] foo: \'bar\' }'); - -var num = new Number(13.37); -num.foo = 'bar'; -assert.equal(util.inspect(num), '{ [Number: 13.37] foo: \'bar\' }'); - -// test es6 Symbol -if (typeof Symbol !== 'undefined') { - assert.equal(util.inspect(Symbol()), 'Symbol()'); - assert.equal(util.inspect(Symbol(123)), 'Symbol(123)'); - assert.equal(util.inspect(Symbol('hi')), 'Symbol(hi)'); - assert.equal(util.inspect([Symbol()]), '[ Symbol() ]'); - assert.equal(util.inspect({ foo: Symbol() }), '{ foo: Symbol() }'); -} diff --git a/test/simple/test-util-log.js b/test/simple/test-util-log.js deleted file mode 100644 index 1912c69f8..000000000 --- a/test/simple/test-util-log.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var assert = require('assert'); -var util = require('util'); - -assert.ok(process.stdout.writable); -assert.ok(process.stderr.writable); - -var stdout_write = global.process.stdout.write; -var strings = []; -global.process.stdout.write = function(string) { - strings.push(string); -}; -console._stderr = process.stdout; - -var tests = [ - {input: 'foo', output: 'foo'}, - {input: undefined, output: 'undefined'}, - {input: null, output: 'null'}, - {input: false, output: 'false'}, - {input: 42, output: '42'}, - {input: function(){}, output: '[Function]'}, - {input: parseInt('not a number', 10), output: 'NaN'}, - {input: {answer: 42}, output: '{ answer: 42 }'}, - {input: [1,2,3], output: '[ 1, 2, 3 ]'} -]; - -// test util.log() -tests.forEach(function(test) { - util.log(test.input); - var result = strings.shift().trim(), - re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/), - match = re.exec(result); - assert.ok(match); - assert.equal(match[1], test.output); -}); - -global.process.stdout.write = stdout_write; diff --git a/test/simple/test-util.js b/test/simple/test-util.js deleted file mode 100644 index 4e75d512c..000000000 --- a/test/simple/test-util.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var common = require('../common'); -var assert = require('assert'); -var util = require('util'); -var context = require('vm').runInNewContext; - -// isArray -assert.equal(true, util.isArray([])); -assert.equal(true, util.isArray(Array())); -assert.equal(true, util.isArray(new Array())); -assert.equal(true, util.isArray(new Array(5))); -assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); -assert.equal(true, util.isArray(context('Array')())); -assert.equal(false, util.isArray({})); -assert.equal(false, util.isArray({ push: function() {} })); -assert.equal(false, util.isArray(/regexp/)); -assert.equal(false, util.isArray(new Error)); -assert.equal(false, util.isArray(Object.create(Array.prototype))); - -// isRegExp -assert.equal(true, util.isRegExp(/regexp/)); -assert.equal(true, util.isRegExp(RegExp())); -assert.equal(true, util.isRegExp(new RegExp())); -assert.equal(true, util.isRegExp(context('RegExp')())); -assert.equal(false, util.isRegExp({})); -assert.equal(false, util.isRegExp([])); -assert.equal(false, util.isRegExp(new Date())); -assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); - -// isDate -assert.equal(true, util.isDate(new Date())); -assert.equal(true, util.isDate(new Date(0))); -assert.equal(true, util.isDate(new (context('Date')))); -assert.equal(false, util.isDate(Date())); -assert.equal(false, util.isDate({})); -assert.equal(false, util.isDate([])); -assert.equal(false, util.isDate(new Error)); -assert.equal(false, util.isDate(Object.create(Date.prototype))); - -// isError -assert.equal(true, util.isError(new Error)); -assert.equal(true, util.isError(new TypeError)); -assert.equal(true, util.isError(new SyntaxError)); -assert.equal(true, util.isError(new (context('Error')))); -assert.equal(true, util.isError(new (context('TypeError')))); -assert.equal(true, util.isError(new (context('SyntaxError')))); -assert.equal(false, util.isError({})); -assert.equal(false, util.isError({ name: 'Error', message: '' })); -assert.equal(false, util.isError([])); -assert.equal(true, util.isError(Object.create(Error.prototype))); - -// isObject -assert.ok(util.isObject({}) === true); - -// _extend -assert.deepEqual(util._extend({a:1}), {a:1}); -assert.deepEqual(util._extend({a:1}, []), {a:1}); -assert.deepEqual(util._extend({a:1}, null), {a:1}); -assert.deepEqual(util._extend({a:1}, true), {a:1}); -assert.deepEqual(util._extend({a:1}, false), {a:1}); -assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); -assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); diff --git a/test/simple/test-v8-flags.js b/test/simple/test-v8-flags.js deleted file mode 100644 index 1397d8bed..000000000 --- a/test/simple/test-v8-flags.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2014, StrongLoop Inc. -// -// Permission to use, copy, modify, and/or distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var v8 = require('v8'); -var vm = require('vm'); - -v8.setFlagsFromString('--allow_natives_syntax'); -assert(eval('%_IsSmi(42)')); -assert(vm.runInThisContext('%_IsSmi(42)')); - -v8.setFlagsFromString('--noallow_natives_syntax'); -assert.throws(function() { eval('%_IsSmi(42)') }, SyntaxError); -assert.throws(function() { vm.runInThisContext('%_IsSmi(42)') }, SyntaxError); diff --git a/test/simple/test-v8-gc.js b/test/simple/test-v8-gc.js deleted file mode 100644 index 4bce8099d..000000000 --- a/test/simple/test-v8-gc.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2014, StrongLoop Inc. -// -// Permission to use, copy, modify, and/or distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// Flags: --expose_gc - -var common = require('../common'); -var assert = require('assert'); -var v8 = require('v8'); - -assert(typeof gc === 'function', 'Run this test with --expose_gc.'); - -var ncalls = 0; -var before; -var after; - -function ongc(before_, after_) { - // Try very hard to not create garbage because that could kick off another - // garbage collection cycle. - before = before_; - after = after_; - ncalls += 1; -} - -gc(); -v8.on('gc', ongc); -gc(); -v8.removeListener('gc', ongc); -gc(); - -assert.equal(ncalls, 1); -assert.equal(typeof before, 'object'); -assert.equal(typeof after, 'object'); -assert.equal(typeof before.timestamp, 'number'); -assert.equal(typeof after.timestamp, 'number'); -assert.equal(before.timestamp <= after.timestamp, true); diff --git a/test/simple/test-v8-stats.js b/test/simple/test-v8-stats.js deleted file mode 100644 index d4623363a..000000000 --- a/test/simple/test-v8-stats.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2014, StrongLoop Inc. -// -// Permission to use, copy, modify, and/or distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var v8 = require('v8'); - -var s = v8.getHeapStatistics(); -var keys = [ - 'heap_size_limit', - 'total_heap_size', - 'total_heap_size_executable', - 'total_physical_size', - 'used_heap_size']; -assert.deepEqual(Object.keys(s).sort(), keys); -keys.forEach(function(key) { - assert.equal(typeof s[key], 'number'); -}); diff --git a/test/simple/test-vm-basic.js b/test/simple/test-vm-basic.js deleted file mode 100644 index 680a81a4b..000000000 --- a/test/simple/test-vm-basic.js +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -// Test 1: vm.runInNewContext -var sandbox = {}; -var result = vm.runInNewContext( - 'foo = "bar"; this.typeofProcess = typeof process; typeof Object;', - sandbox -); -assert.deepEqual(sandbox, { - foo: 'bar', - typeofProcess: 'undefined', -}); -assert.strictEqual(result, 'function'); - -// Test 2: vm.runInContext -var sandbox2 = { foo: 'bar' }; -var context = vm.createContext(sandbox2); -var result = vm.runInContext( - 'baz = foo; this.typeofProcess = typeof process; typeof Object;', - context -); -assert.deepEqual(sandbox2, { - foo: 'bar', - baz: 'bar', - typeofProcess: 'undefined' -}); -assert.strictEqual(result, 'function'); - -// Test 3: vm.runInThisContext -var result = vm.runInThisContext( - 'vmResult = "foo"; Object.prototype.toString.call(process);' -); -assert.strictEqual(global.vmResult, 'foo'); -assert.strictEqual(result, '[object process]'); -delete global.vmResult; - -// Test 4: vm.runInNewContext -var result = vm.runInNewContext( - 'vmResult = "foo"; typeof process;' -); -assert.strictEqual(global.vmResult, undefined); -assert.strictEqual(result, 'undefined'); - -// Test 5: vm.createContext -var sandbox3 = {}; -var context2 = vm.createContext(sandbox3); -assert.strictEqual(sandbox3, context2); diff --git a/test/simple/test-vm-context-async-script.js b/test/simple/test-vm-context-async-script.js deleted file mode 100644 index d201e98eb..000000000 --- a/test/simple/test-vm-context-async-script.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -var sandbox = { setTimeout: setTimeout }; - -var ctx = vm.createContext(sandbox); - -vm.runInContext('setTimeout(function() { x = 3; }, 0);', ctx); -setTimeout(function () { - assert.strictEqual(sandbox.x, 3); - assert.strictEqual(ctx.x, 3); -}, 1); diff --git a/test/simple/test-vm-context-property-forwarding.js b/test/simple/test-vm-context-property-forwarding.js deleted file mode 100644 index 6d51463ad..000000000 --- a/test/simple/test-vm-context-property-forwarding.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -var sandbox = { x: 3 }; - -var ctx = vm.createContext(sandbox); - -assert.strictEqual(vm.runInContext('x;', ctx), 3); -vm.runInContext('y = 4;', ctx); -assert.strictEqual(sandbox.y, 4); -assert.strictEqual(ctx.y, 4); diff --git a/test/simple/test-vm-context.js b/test/simple/test-vm-context.js deleted file mode 100644 index c843addc6..000000000 --- a/test/simple/test-vm-context.js +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var vm = require('vm'); -var Script = vm.Script; -var script = new Script('"passed";'); - -console.error('run in a new empty context'); -var context = vm.createContext(); -var result = script.runInContext(context); -assert.equal('passed', result); - -console.error('create a new pre-populated context'); -context = vm.createContext({'foo': 'bar', 'thing': 'lala'}); -assert.equal('bar', context.foo); -assert.equal('lala', context.thing); - -console.error('test updating context'); -script = new Script('foo = 3;'); -result = script.runInContext(context); -assert.equal(3, context.foo); -assert.equal('lala', context.thing); - -// Issue GH-227: -assert.throws(function () { - vm.runInNewContext('', null, 'some.js'); -}, TypeError); - -// Issue GH-1140: -console.error('test runInContext signature'); -var gh1140Exception; -try { - vm.runInContext('throw new Error()', context, 'expected-filename.js'); -} -catch (e) { - gh1140Exception = e; - assert.ok(/expected-filename/.test(e.stack), - 'expected appearance of filename in Error stack'); -} -assert.ok(gh1140Exception, - 'expected exception from runInContext signature test'); - -// GH-558, non-context argument segfaults / raises assertion -[undefined, null, 0, 0.0, '', {}, []].forEach(function(e) { - assert.throws(function() { script.runInContext(e); }, TypeError); - assert.throws(function() { vm.runInContext('', e); }, TypeError); -}); - -// Issue GH-693: -console.error('test RegExp as argument to assert.throws'); -script = vm.createScript('var assert = require(\'assert\'); assert.throws(' + - 'function() { throw "hello world"; }, /hello/);', - 'some.js'); -script.runInNewContext({ require : require }); - -// Issue GH-7529 -script = vm.createScript('delete b'); -var ctx = {}; -Object.defineProperty(ctx, 'b', { configurable: false }); -ctx = vm.createContext(ctx); -assert.equal(script.runInContext(ctx), false); diff --git a/test/simple/test-vm-create-and-run-in-context.js b/test/simple/test-vm-create-and-run-in-context.js deleted file mode 100644 index 863569ce7..000000000 --- a/test/simple/test-vm-create-and-run-in-context.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var vm = require('vm'); - -console.error('run in a new empty context'); -var context = vm.createContext(); -var result = vm.runInContext('"passed";', context); -assert.equal('passed', result); - -console.error('create a new pre-populated context'); -context = vm.createContext({'foo': 'bar', 'thing': 'lala'}); -assert.equal('bar', context.foo); -assert.equal('lala', context.thing); - -console.error('test updating context'); -result = vm.runInContext('var foo = 3;', context); -assert.equal(3, context.foo); -assert.equal('lala', context.thing); diff --git a/test/simple/test-vm-create-context-accessors.js b/test/simple/test-vm-create-context-accessors.js deleted file mode 100644 index f0622245b..000000000 --- a/test/simple/test-vm-create-context-accessors.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -var ctx = {}; - -Object.defineProperty(ctx, 'getter', { - get: function() { - return 'ok'; - } -}); - -var val; -Object.defineProperty(ctx, 'setter', { - set: function(_val) { - val = _val; - }, - get: function() { - return 'ok=' + val; - } -}); - -ctx = vm.createContext(ctx); - -var result = vm.runInContext('setter = "test";[getter,setter]', ctx); -assert.deepEqual(result, ['ok', 'ok=test']); diff --git a/test/simple/test-vm-create-context-arg.js b/test/simple/test-vm-create-context-arg.js deleted file mode 100644 index 8c49a3736..000000000 --- a/test/simple/test-vm-create-context-arg.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -assert.throws(function() { - var ctx = vm.createContext('string is not supported'); -}, TypeError); - -assert.doesNotThrow(function() { - var ctx = vm.createContext({ a: 1 }); - ctx = vm.createContext([0, 1, 2, 3]); -}); - -assert.doesNotThrow(function() { - var sandbox = {}; - vm.createContext(sandbox); - vm.createContext(sandbox); -}); diff --git a/test/simple/test-vm-create-context-circular-reference.js b/test/simple/test-vm-create-context-circular-reference.js deleted file mode 100644 index ae5b48c81..000000000 --- a/test/simple/test-vm-create-context-circular-reference.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -var sbx = {}; -sbx.window = sbx; - -sbx = vm.createContext(sbx); - -sbx.test = 123; - -assert.equal(sbx.window.window.window.window.window.test, 123); - diff --git a/test/simple/test-vm-cross-context.js b/test/simple/test-vm-cross-context.js deleted file mode 100644 index 6f5d501fe..000000000 --- a/test/simple/test-vm-cross-context.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var vm = require('vm'); -var ctx = vm.createContext(global); - -assert.doesNotThrow(function() { - vm.runInContext("!function() { var x = console.log; }()", ctx); -}); diff --git a/test/simple/test-vm-debug-context.js b/test/simple/test-vm-debug-context.js deleted file mode 100644 index 5569b3853..000000000 --- a/test/simple/test-vm-debug-context.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -assert.throws(function() { - vm.runInDebugContext('*'); -}, /SyntaxError/); - -assert.throws(function() { - vm.runInDebugContext({ toString: assert.fail }); -}, /AssertionError/); - -assert.throws(function() { - vm.runInDebugContext('throw URIError("BAM")'); -}, /URIError/); - -assert.throws(function() { - vm.runInDebugContext('(function(f) { f(f) })(function(f) { f(f) })'); -}, /RangeError/); - -assert.equal(typeof(vm.runInDebugContext('this')), 'object'); -assert.equal(typeof(vm.runInDebugContext('Debug')), 'object'); - -assert.strictEqual(vm.runInDebugContext(), undefined); -assert.strictEqual(vm.runInDebugContext(0), 0); -assert.strictEqual(vm.runInDebugContext(null), null); -assert.strictEqual(vm.runInDebugContext(undefined), undefined); diff --git a/test/simple/test-vm-function-declaration.js b/test/simple/test-vm-function-declaration.js deleted file mode 100644 index 58772ba2f..000000000 --- a/test/simple/test-vm-function-declaration.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var vm = require('vm'); -var o = vm.createContext({ console: console }); - -// This triggers the setter callback in node_contextify.cc -var code = 'var a = function() {};\n'; - -// but this does not, since function decls are defineProperties, -// not simple sets. -code += 'function b(){}\n'; - -// Grab the global b function as the completion value, to ensure that -// we are getting the global function, and not some other thing -code += '(function(){return this})().b;\n' - -var res = vm.runInContext(code, o, 'test'); - -assert.equal(typeof res, 'function', 'result should be function'); -assert.equal(res.name, 'b', 'res should be named b'); -assert.equal(typeof o.a, 'function', 'a should be function'); -assert.equal(typeof o.b, 'function', 'b should be function'); -assert.equal(res, o.b, 'result should be global b function'); - -console.log('ok'); diff --git a/test/simple/test-vm-global-define-property.js b/test/simple/test-vm-global-define-property.js deleted file mode 100644 index fcfe489c1..000000000 --- a/test/simple/test-vm-global-define-property.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var vm = require('vm'); - -var code = - 'Object.defineProperty(this, "f", {\n' + - ' get: function() { return x; },\n' + - ' set: function(k) { x = k; },\n' + - ' configurable: true,\n' + - ' enumerable: true\n' + - '});\n' + - 'g = f;\n' + - 'f;\n'; - -var x = {}; -var o = vm.createContext({ console: console, x: x }); - -var res = vm.runInContext(code, o, 'test'); - -assert(res); -assert.equal(typeof res, 'object'); -assert.equal(res, x); -assert.equal(o.f, res); -assert.deepEqual(Object.keys(o), ['console', 'x', 'g', 'f']); diff --git a/test/simple/test-vm-global-identity.js b/test/simple/test-vm-global-identity.js deleted file mode 100644 index adfb32358..000000000 --- a/test/simple/test-vm-global-identity.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -var ctx = vm.createContext(); -ctx.window = ctx; - -var thisVal = vm.runInContext('this;', ctx); -var windowVal = vm.runInContext('window;', ctx); -assert.strictEqual(thisVal, windowVal); diff --git a/test/simple/test-vm-harmony-proxies.js b/test/simple/test-vm-harmony-proxies.js deleted file mode 100644 index e1b4ec8ad..000000000 --- a/test/simple/test-vm-harmony-proxies.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Flags: --harmony_proxies - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -// src/node_contextify.cc filters out the Proxy object from the parent -// context. Make sure that the new context has a Proxy object of its own. -var sandbox = {}; -var result = vm.runInNewContext('this.Proxy = Proxy', sandbox); -assert(typeof sandbox.Proxy === 'object'); -assert(sandbox.Proxy !== Proxy); - -// Unless we copy the Proxy object explicitly, of course. -var sandbox = { Proxy: Proxy }; -var result = vm.runInNewContext('this.Proxy = Proxy', sandbox); -assert(typeof sandbox.Proxy === 'object'); -assert(sandbox.Proxy === Proxy); diff --git a/test/simple/test-vm-harmony-symbols.js b/test/simple/test-vm-harmony-symbols.js deleted file mode 100644 index 200084fdf..000000000 --- a/test/simple/test-vm-harmony-symbols.js +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -// The sandbox should have its own Symbol constructor. -var sandbox = {}; -var result = vm.runInNewContext('this.Symbol = Symbol', sandbox); -assert(typeof sandbox.Symbol === 'function'); -assert(sandbox.Symbol !== Symbol); - -// Unless we copy the Symbol constructor explicitly, of course. -var sandbox = { Symbol: Symbol }; -var result = vm.runInNewContext('this.Symbol = Symbol', sandbox); -assert(typeof sandbox.Symbol === 'function'); -assert(sandbox.Symbol === Symbol); diff --git a/test/simple/test-vm-is-context.js b/test/simple/test-vm-is-context.js deleted file mode 100644 index 9ef2037fe..000000000 --- a/test/simple/test-vm-is-context.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -assert.throws(function() { - vm.isContext('string is not supported'); -}, TypeError); - -assert.strictEqual(vm.isContext({}), false); -assert.strictEqual(vm.isContext([]), false); - -assert.strictEqual(vm.isContext(vm.createContext()), true); -assert.strictEqual(vm.isContext(vm.createContext([])), true); - -var sandbox = { foo: 'bar' }; -vm.createContext(sandbox); -assert.strictEqual(vm.isContext(sandbox), true); diff --git a/test/simple/test-vm-new-script-new-context.js b/test/simple/test-vm-new-script-new-context.js deleted file mode 100644 index 139d85429..000000000 --- a/test/simple/test-vm-new-script-new-context.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var Script = require('vm').Script; - -common.globalCheck = false; - -console.error('run a string'); -var script = new Script('\'passed\';'); -console.error('script created'); -var result1 = script.runInNewContext(); -var result2 = script.runInNewContext(); -assert.equal('passed', result1); -assert.equal('passed', result2); - -console.error('thrown error'); -script = new Script('throw new Error(\'test\');'); -assert.throws(function() { - script.runInNewContext(); -}, /test/); - - - -console.error('undefined reference'); -var error; -script = new Script('foo.bar = 5;'); -assert.throws(function () { - script.runInNewContext(); -}, /not defined/); - - -hello = 5; -script = new Script('hello = 2'); -script.runInNewContext(); -assert.equal(5, hello); - - -console.error('pass values in and out'); -code = 'foo = 1;' + - 'bar = 2;' + - 'if (baz !== 3) throw new Error(\'test fail\');'; -foo = 2; -obj = { foo: 0, baz: 3 }; -script = new Script(code); -var baz = script.runInNewContext(obj); -assert.equal(1, obj.foo); -assert.equal(2, obj.bar); -assert.equal(2, foo); - -console.error('call a function by reference'); -script = new Script('f()'); -function changeFoo() { foo = 100 } -script.runInNewContext({ f: changeFoo }); -assert.equal(foo, 100); - -console.error('modify an object by reference'); -script = new Script('f.a = 2'); -var f = { a: 1 }; -script.runInNewContext({ f: f }); -assert.equal(f.a, 2); - -assert.throws(function() { - script.runInNewContext(); -}, /f is not defined/); - -console.error('invalid this'); -assert.throws(function() { - script.runInNewContext.call('\'hello\';'); -}, TypeError); - - diff --git a/test/simple/test-vm-new-script-this-context.js b/test/simple/test-vm-new-script-this-context.js deleted file mode 100644 index ff0b5b36f..000000000 --- a/test/simple/test-vm-new-script-this-context.js +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var Script = require('vm').Script; - -common.globalCheck = false; - -console.error('run a string'); -var script = new Script('\'passed\';'); -var result = script.runInThisContext(script); -assert.equal('passed', result); - -console.error('thrown error'); -script = new Script('throw new Error(\'test\');'); -assert.throws(function() { - script.runInThisContext(script); -}); - -hello = 5; -script = new Script('hello = 2'); -script.runInThisContext(script); -assert.equal(2, hello); - - -console.error('pass values'); -code = 'foo = 1;' + - 'bar = 2;' + - 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; -foo = 2; -obj = { foo: 0, baz: 3 }; -script = new Script(code); -script.runInThisContext(script); -assert.equal(0, obj.foo); -assert.equal(2, bar); -assert.equal(1, foo); - -console.error('call a function'); -f = function() { foo = 100 }; -script = new Script('f()'); -script.runInThisContext(script); -assert.equal(100, foo); diff --git a/test/simple/test-vm-run-in-new-context.js b/test/simple/test-vm-run-in-new-context.js deleted file mode 100644 index ecb80bdbc..000000000 --- a/test/simple/test-vm-run-in-new-context.js +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Flags: --expose-gc - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -assert.equal(typeof gc, 'function', 'Run this test with --expose-gc'); - -common.globalCheck = false; - -console.error('run a string'); -var result = vm.runInNewContext('\'passed\';'); -assert.equal('passed', result); - -console.error('thrown error'); -assert.throws(function() { - vm.runInNewContext('throw new Error(\'test\');'); -}); - -hello = 5; -vm.runInNewContext('hello = 2'); -assert.equal(5, hello); - - -console.error('pass values in and out'); -code = 'foo = 1;' + - 'bar = 2;' + - 'if (baz !== 3) throw new Error(\'test fail\');'; -foo = 2; -obj = { foo: 0, baz: 3 }; -var baz = vm.runInNewContext(code, obj); -assert.equal(1, obj.foo); -assert.equal(2, obj.bar); -assert.equal(2, foo); - -console.error('call a function by reference'); -function changeFoo() { foo = 100 } -vm.runInNewContext('f()', { f: changeFoo }); -assert.equal(foo, 100); - -console.error('modify an object by reference'); -var f = { a: 1 }; -vm.runInNewContext('f.a = 2', { f: f }); -assert.equal(f.a, 2); - -console.error('use function in context without referencing context'); -var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }) -gc(); -fn(); -// Should not crash diff --git a/test/simple/test-vm-static-this.js b/test/simple/test-vm-static-this.js deleted file mode 100644 index 860fbf04d..000000000 --- a/test/simple/test-vm-static-this.js +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -common.globalCheck = false; - -console.error('run a string'); -var result = vm.runInThisContext('\'passed\';'); -assert.equal('passed', result); - -console.error('thrown error'); -assert.throws(function() { - vm.runInThisContext('throw new Error(\'test\');'); -}, /test/); - -hello = 5; -vm.runInThisContext('hello = 2'); -assert.equal(2, hello); - - -console.error('pass values'); -code = 'foo = 1;' + - 'bar = 2;' + - 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');'; -foo = 2; -obj = { foo: 0, baz: 3 }; -var baz = vm.runInThisContext(code); -assert.equal(0, obj.foo); -assert.equal(2, bar); -assert.equal(1, foo); - -console.error('call a function'); -f = function() { foo = 100 }; -vm.runInThisContext('f()'); -assert.equal(100, foo); diff --git a/test/simple/test-vm-syntax-error-stderr.js b/test/simple/test-vm-syntax-error-stderr.js deleted file mode 100644 index 3e88e1ff1..000000000 --- a/test/simple/test-vm-syntax-error-stderr.js +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var path = require('path'); -var child_process = require('child_process'); - -var wrong_script = path.join(common.fixturesDir, 'cert.pem'); - -var p = child_process.spawn(process.execPath, [ - '-e', - 'try { require(process.argv[1]); } catch (e) { console.log(e.stack); }', - wrong_script -]); - -p.stderr.on('data', function(data) { - assert(false, 'Unexpected stderr data: ' + data); -}); - -var output = ''; - -p.stdout.on('data', function(data) { - output += data; -}); - -process.on('exit', function() { - assert(/BEGIN CERT/.test(output)); - assert(/^\s+\^/m.test(output)); - assert(/Invalid left-hand side expression in prefix operation/.test(output)); -}); diff --git a/test/simple/test-vm-timeout-rethrow.js b/test/simple/test-vm-timeout-rethrow.js deleted file mode 100644 index c2158a135..000000000 --- a/test/simple/test-vm-timeout-rethrow.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var assert = require('assert'); -var vm = require('vm'); -var spawn = require('child_process').spawn; - -if (process.argv[2] === 'child') { - var code = 'var j = 0;\n' + - 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' - 'j;'; - - var ctx = vm.createContext({ - add: function(x, y) { - return x + y; - } - }); - - vm.runInContext(code, ctx, { timeout: 1 }); -} else { - var proc = spawn(process.execPath, process.argv.slice(1).concat('child')); - var err = ''; - proc.stderr.on('data', function(data) { - err += data; - }); - - process.on('exit', function() { - assert.ok(/Script execution timed out/.test(err)); - }); -} diff --git a/test/simple/test-vm-timeout.js b/test/simple/test-vm-timeout.js deleted file mode 100644 index 8ad2a234b..000000000 --- a/test/simple/test-vm-timeout.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var vm = require('vm'); - -// Test 1: Timeout of 100ms executing endless loop -assert.throws(function() { - vm.runInThisContext('while(true) {}', { timeout: 100 }); -}); - -// Test 2: Timeout must be >= 0ms -assert.throws(function() { - vm.runInThisContext('', { timeout: -1 }); -}, RangeError); - -// Test 3: Timeout of 0ms -assert.throws(function() { - vm.runInThisContext('', { timeout: 0 }); -}, RangeError); - -// Test 4: Timeout of 1000ms, script finishes first -vm.runInThisContext('', { timeout: 1000 }); - -// Test 5: Nested vm timeouts, inner timeout propagates out -assert.throws(function() { - var context = { - log: console.log, - runInVM: function(timeout) { - vm.runInNewContext('while(true) {}', context, { timeout: timeout }); - } - }; - vm.runInNewContext('runInVM(10)', context, { timeout: 100 }); - throw new Error('Test 5 failed'); -}, /Script execution timed out./); diff --git a/test/simple/test-writedouble.js b/test/simple/test-writedouble.js deleted file mode 100644 index a700a82b4..000000000 --- a/test/simple/test-writedouble.js +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * Tests to verify we're writing doubles correctly - */ -var common = require('../common'); -var ASSERT = require('assert'); - -function test(clazz) { - var buffer = new clazz(16); - - buffer.writeDoubleBE(2.225073858507201e-308, 0); - buffer.writeDoubleLE(2.225073858507201e-308, 8); - ASSERT.equal(0x00, buffer[0]); - ASSERT.equal(0x0f, buffer[1]); - ASSERT.equal(0xff, buffer[2]); - ASSERT.equal(0xff, buffer[3]); - ASSERT.equal(0xff, buffer[4]); - ASSERT.equal(0xff, buffer[5]); - ASSERT.equal(0xff, buffer[6]); - ASSERT.equal(0xff, buffer[7]); - ASSERT.equal(0xff, buffer[8]); - ASSERT.equal(0xff, buffer[9]); - ASSERT.equal(0xff, buffer[10]); - ASSERT.equal(0xff, buffer[11]); - ASSERT.equal(0xff, buffer[12]); - ASSERT.equal(0xff, buffer[13]); - ASSERT.equal(0x0f, buffer[14]); - ASSERT.equal(0x00, buffer[15]); - - buffer.writeDoubleBE(1.0000000000000004, 0); - buffer.writeDoubleLE(1.0000000000000004, 8); - ASSERT.equal(0x3f, buffer[0]); - ASSERT.equal(0xf0, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x02, buffer[7]); - ASSERT.equal(0x02, buffer[8]); - ASSERT.equal(0x00, buffer[9]); - ASSERT.equal(0x00, buffer[10]); - ASSERT.equal(0x00, buffer[11]); - ASSERT.equal(0x00, buffer[12]); - ASSERT.equal(0x00, buffer[13]); - ASSERT.equal(0xf0, buffer[14]); - ASSERT.equal(0x3f, buffer[15]); - - buffer.writeDoubleBE(-2, 0); - buffer.writeDoubleLE(-2, 8); - ASSERT.equal(0xc0, buffer[0]); - ASSERT.equal(0x00, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - ASSERT.equal(0x00, buffer[8]); - ASSERT.equal(0x00, buffer[9]); - ASSERT.equal(0x00, buffer[10]); - ASSERT.equal(0x00, buffer[11]); - ASSERT.equal(0x00, buffer[12]); - ASSERT.equal(0x00, buffer[13]); - ASSERT.equal(0x00, buffer[14]); - ASSERT.equal(0xc0, buffer[15]); - - buffer.writeDoubleBE(1.7976931348623157e+308, 0); - buffer.writeDoubleLE(1.7976931348623157e+308, 8); - ASSERT.equal(0x7f, buffer[0]); - ASSERT.equal(0xef, buffer[1]); - ASSERT.equal(0xff, buffer[2]); - ASSERT.equal(0xff, buffer[3]); - ASSERT.equal(0xff, buffer[4]); - ASSERT.equal(0xff, buffer[5]); - ASSERT.equal(0xff, buffer[6]); - ASSERT.equal(0xff, buffer[7]); - ASSERT.equal(0xff, buffer[8]); - ASSERT.equal(0xff, buffer[9]); - ASSERT.equal(0xff, buffer[10]); - ASSERT.equal(0xff, buffer[11]); - ASSERT.equal(0xff, buffer[12]); - ASSERT.equal(0xff, buffer[13]); - ASSERT.equal(0xef, buffer[14]); - ASSERT.equal(0x7f, buffer[15]); - - buffer.writeDoubleBE(0 * -1, 0); - buffer.writeDoubleLE(0 * -1, 8); - ASSERT.equal(0x80, buffer[0]); - ASSERT.equal(0x00, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - ASSERT.equal(0x00, buffer[8]); - ASSERT.equal(0x00, buffer[9]); - ASSERT.equal(0x00, buffer[10]); - ASSERT.equal(0x00, buffer[11]); - ASSERT.equal(0x00, buffer[12]); - ASSERT.equal(0x00, buffer[13]); - ASSERT.equal(0x00, buffer[14]); - ASSERT.equal(0x80, buffer[15]); - - buffer.writeDoubleBE(Infinity, 0); - buffer.writeDoubleLE(Infinity, 8); - ASSERT.equal(0x7F, buffer[0]); - ASSERT.equal(0xF0, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - ASSERT.equal(0x00, buffer[8]); - ASSERT.equal(0x00, buffer[9]); - ASSERT.equal(0x00, buffer[10]); - ASSERT.equal(0x00, buffer[11]); - ASSERT.equal(0x00, buffer[12]); - ASSERT.equal(0x00, buffer[13]); - ASSERT.equal(0xF0, buffer[14]); - ASSERT.equal(0x7F, buffer[15]); - ASSERT.equal(Infinity, buffer.readDoubleBE(0)); - ASSERT.equal(Infinity, buffer.readDoubleLE(8)); - - buffer.writeDoubleBE(-Infinity, 0); - buffer.writeDoubleLE(-Infinity, 8); - ASSERT.equal(0xFF, buffer[0]); - ASSERT.equal(0xF0, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - ASSERT.equal(0x00, buffer[8]); - ASSERT.equal(0x00, buffer[9]); - ASSERT.equal(0x00, buffer[10]); - ASSERT.equal(0x00, buffer[11]); - ASSERT.equal(0x00, buffer[12]); - ASSERT.equal(0x00, buffer[13]); - ASSERT.equal(0xF0, buffer[14]); - ASSERT.equal(0xFF, buffer[15]); - ASSERT.equal(-Infinity, buffer.readDoubleBE(0)); - ASSERT.equal(-Infinity, buffer.readDoubleLE(8)); - - buffer.writeDoubleBE(NaN, 0); - buffer.writeDoubleLE(NaN, 8); - // Darwin ia32 does the other kind of NaN. - // Compiler bug. No one really cares. - ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); - // mips processors use a slightly different NaN - ASSERT(0xF8 === buffer[1] || 0xF7 === buffer[1]); - ASSERT(0x00 === buffer[2] || 0xFF === buffer[2]); - ASSERT(0x00 === buffer[3] || 0xFF === buffer[3]); - ASSERT(0x00 === buffer[4] || 0xFF === buffer[4]); - ASSERT(0x00 === buffer[5] || 0xFF === buffer[5]); - ASSERT(0x00 === buffer[6] || 0xFF === buffer[6]); - ASSERT(0x00 === buffer[7] || 0xFF === buffer[7]); - ASSERT(0x00 === buffer[8] || 0xFF === buffer[8]); - ASSERT(0x00 === buffer[9] || 0xFF === buffer[9]); - ASSERT(0x00 === buffer[10] || 0xFF === buffer[10]); - ASSERT(0x00 === buffer[11] || 0xFF === buffer[11]); - ASSERT(0x00 === buffer[12] || 0xFF === buffer[12]); - ASSERT(0x00 === buffer[13] || 0xFF === buffer[13]); - ASSERT(0xF8 === buffer[14] || 0xF7 === buffer[14]); - // Darwin ia32 does the other kind of NaN. - // Compiler bug. No one really cares. - ASSERT(0x7F === buffer[15] || 0xFF === buffer[15]); - ASSERT.ok(isNaN(buffer.readDoubleBE(0))); - ASSERT.ok(isNaN(buffer.readDoubleLE(8))); -} - - -test(Buffer); diff --git a/test/simple/test-writefloat.js b/test/simple/test-writefloat.js deleted file mode 100644 index 0b4d21532..000000000 --- a/test/simple/test-writefloat.js +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * Tests to verify we're writing floats correctly - */ -var common = require('../common'); -var ASSERT = require('assert'); - -function test(clazz) { - var buffer = new clazz(8); - - buffer.writeFloatBE(1, 0); - buffer.writeFloatLE(1, 4); - ASSERT.equal(0x3f, buffer[0]); - ASSERT.equal(0x80, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x80, buffer[6]); - ASSERT.equal(0x3f, buffer[7]); - - buffer.writeFloatBE(1 / 3, 0); - buffer.writeFloatLE(1 / 3, 4); - ASSERT.equal(0x3e, buffer[0]); - ASSERT.equal(0xaa, buffer[1]); - ASSERT.equal(0xaa, buffer[2]); - ASSERT.equal(0xab, buffer[3]); - ASSERT.equal(0xab, buffer[4]); - ASSERT.equal(0xaa, buffer[5]); - ASSERT.equal(0xaa, buffer[6]); - ASSERT.equal(0x3e, buffer[7]); - - buffer.writeFloatBE(3.4028234663852886e+38, 0); - buffer.writeFloatLE(3.4028234663852886e+38, 4); - ASSERT.equal(0x7f, buffer[0]); - ASSERT.equal(0x7f, buffer[1]); - ASSERT.equal(0xff, buffer[2]); - ASSERT.equal(0xff, buffer[3]); - ASSERT.equal(0xff, buffer[4]); - ASSERT.equal(0xff, buffer[5]); - ASSERT.equal(0x7f, buffer[6]); - ASSERT.equal(0x7f, buffer[7]); - - buffer.writeFloatLE(1.1754943508222875e-38, 0); - buffer.writeFloatBE(1.1754943508222875e-38, 4); - ASSERT.equal(0x00, buffer[0]); - ASSERT.equal(0x00, buffer[1]); - ASSERT.equal(0x80, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x80, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - - buffer.writeFloatBE(0 * -1, 0); - buffer.writeFloatLE(0 * -1, 4); - ASSERT.equal(0x80, buffer[0]); - ASSERT.equal(0x00, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x80, buffer[7]); - - buffer.writeFloatBE(Infinity, 0); - buffer.writeFloatLE(Infinity, 4); - ASSERT.equal(0x7F, buffer[0]); - ASSERT.equal(0x80, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x80, buffer[6]); - ASSERT.equal(0x7F, buffer[7]); - ASSERT.equal(Infinity, buffer.readFloatBE(0)); - ASSERT.equal(Infinity, buffer.readFloatLE(4)); - - buffer.writeFloatBE(-Infinity, 0); - buffer.writeFloatLE(-Infinity, 4); - // Darwin ia32 does the other kind of NaN. - // Compiler bug. No one really cares. - ASSERT(0xFF === buffer[0] || 0x7F === buffer[0]); - ASSERT.equal(0x80, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x80, buffer[6]); - ASSERT.equal(0xFF, buffer[7]); - ASSERT.equal(-Infinity, buffer.readFloatBE(0)); - ASSERT.equal(-Infinity, buffer.readFloatLE(4)); - - buffer.writeFloatBE(NaN, 0); - buffer.writeFloatLE(NaN, 4); - // Darwin ia32 does the other kind of NaN. - // Compiler bug. No one really cares. - ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); - // mips processors use a slightly different NaN - ASSERT(0xC0 === buffer[1] || 0xBF === buffer[1]); - ASSERT(0x00 === buffer[2] || 0xFF === buffer[2]); - ASSERT(0x00 === buffer[3] || 0xFF === buffer[3]); - ASSERT(0x00 === buffer[4] || 0xFF === buffer[4]); - ASSERT(0x00 === buffer[5] || 0xFF === buffer[5]); - ASSERT(0xC0 === buffer[6] || 0xBF === buffer[6]); - // Darwin ia32 does the other kind of NaN. - // Compiler bug. No one really cares. - ASSERT(0x7F === buffer[7] || 0xFF === buffer[7]); - ASSERT.ok(isNaN(buffer.readFloatBE(0))); - ASSERT.ok(isNaN(buffer.readFloatLE(4))); -} - - -test(Buffer); diff --git a/test/simple/test-writeint.js b/test/simple/test-writeint.js deleted file mode 100644 index 10540b6bd..000000000 --- a/test/simple/test-writeint.js +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * Tests to verify we're writing signed integers correctly - */ -var common = require('../common'); -var ASSERT = require('assert'); - -function test8(clazz) { - var buffer = new clazz(2); - - buffer.writeInt8(0x23, 0); - buffer.writeInt8(-5, 1); - - ASSERT.equal(0x23, buffer[0]); - ASSERT.equal(0xfb, buffer[1]); - - /* Make sure we handle truncation correctly */ - ASSERT.throws(function() { - buffer.writeInt8(0xabc, 0); - }); - ASSERT.throws(function() { - buffer.writeInt8(0xabc, 0); - }); - - /* Make sure we handle min/max correctly */ - buffer.writeInt8(0x7f, 0); - buffer.writeInt8(-0x80, 1); - - ASSERT.equal(0x7f, buffer[0]); - ASSERT.equal(0x80, buffer[1]); - ASSERT.throws(function() { - buffer.writeInt8(0x7f + 1, 0); - }); - ASSERT.throws(function() { - buffer.writeInt8(-0x80 - 1, 0); - }); -} - - -function test16(clazz) { - var buffer = new clazz(6); - - buffer.writeInt16BE(0x0023, 0); - buffer.writeInt16LE(0x0023, 2); - ASSERT.equal(0x00, buffer[0]); - ASSERT.equal(0x23, buffer[1]); - ASSERT.equal(0x23, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - - buffer.writeInt16BE(-5, 0); - buffer.writeInt16LE(-5, 2); - ASSERT.equal(0xff, buffer[0]); - ASSERT.equal(0xfb, buffer[1]); - ASSERT.equal(0xfb, buffer[2]); - ASSERT.equal(0xff, buffer[3]); - - buffer.writeInt16BE(-1679, 1); - buffer.writeInt16LE(-1679, 3); - ASSERT.equal(0xf9, buffer[1]); - ASSERT.equal(0x71, buffer[2]); - ASSERT.equal(0x71, buffer[3]); - ASSERT.equal(0xf9, buffer[4]); - - /* Make sure we handle min/max correctly */ - buffer.writeInt16BE(0x7fff, 0); - buffer.writeInt16BE(-0x8000, 2); - ASSERT.equal(0x7f, buffer[0]); - ASSERT.equal(0xff, buffer[1]); - ASSERT.equal(0x80, buffer[2]); - ASSERT.equal(0x00, buffer[3]); - ASSERT.throws(function() { - buffer.writeInt16BE(0x7fff + 1, 0); - }); - ASSERT.throws(function() { - buffer.writeInt16BE(-0x8000 - 1, 0); - }); - - buffer.writeInt16LE(0x7fff, 0); - buffer.writeInt16LE(-0x8000, 2); - ASSERT.equal(0xff, buffer[0]); - ASSERT.equal(0x7f, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x80, buffer[3]); - ASSERT.throws(function() { - buffer.writeInt16LE(0x7fff + 1, 0); - }); - ASSERT.throws(function() { - buffer.writeInt16LE(-0x8000 - 1, 0); - }); -} - - -function test32(clazz) { - var buffer = new clazz(8); - - buffer.writeInt32BE(0x23, 0); - buffer.writeInt32LE(0x23, 4); - ASSERT.equal(0x00, buffer[0]); - ASSERT.equal(0x00, buffer[1]); - ASSERT.equal(0x00, buffer[2]); - ASSERT.equal(0x23, buffer[3]); - ASSERT.equal(0x23, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - - buffer.writeInt32BE(-5, 0); - buffer.writeInt32LE(-5, 4); - ASSERT.equal(0xff, buffer[0]); - ASSERT.equal(0xff, buffer[1]); - ASSERT.equal(0xff, buffer[2]); - ASSERT.equal(0xfb, buffer[3]); - ASSERT.equal(0xfb, buffer[4]); - ASSERT.equal(0xff, buffer[5]); - ASSERT.equal(0xff, buffer[6]); - ASSERT.equal(0xff, buffer[7]); - - buffer.writeInt32BE(-805306713, 0); - buffer.writeInt32LE(-805306713, 4); - ASSERT.equal(0xcf, buffer[0]); - ASSERT.equal(0xff, buffer[1]); - ASSERT.equal(0xfe, buffer[2]); - ASSERT.equal(0xa7, buffer[3]); - ASSERT.equal(0xa7, buffer[4]); - ASSERT.equal(0xfe, buffer[5]); - ASSERT.equal(0xff, buffer[6]); - ASSERT.equal(0xcf, buffer[7]); - - /* Make sure we handle min/max correctly */ - buffer.writeInt32BE(0x7fffffff, 0); - buffer.writeInt32BE(-0x80000000, 4); - ASSERT.equal(0x7f, buffer[0]); - ASSERT.equal(0xff, buffer[1]); - ASSERT.equal(0xff, buffer[2]); - ASSERT.equal(0xff, buffer[3]); - ASSERT.equal(0x80, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x00, buffer[7]); - ASSERT.throws(function() { - buffer.writeInt32BE(0x7fffffff + 1, 0); - }); - ASSERT.throws(function() { - buffer.writeInt32BE(-0x80000000 - 1, 0); - }); - - buffer.writeInt32LE(0x7fffffff, 0); - buffer.writeInt32LE(-0x80000000, 4); - ASSERT.equal(0xff, buffer[0]); - ASSERT.equal(0xff, buffer[1]); - ASSERT.equal(0xff, buffer[2]); - ASSERT.equal(0x7f, buffer[3]); - ASSERT.equal(0x00, buffer[4]); - ASSERT.equal(0x00, buffer[5]); - ASSERT.equal(0x00, buffer[6]); - ASSERT.equal(0x80, buffer[7]); - ASSERT.throws(function() { - buffer.writeInt32LE(0x7fffffff + 1, 0); - }); - ASSERT.throws(function() { - buffer.writeInt32LE(-0x80000000 - 1, 0); - }); -} - - -test8(Buffer); -test16(Buffer); -test32(Buffer); diff --git a/test/simple/test-writeuint.js b/test/simple/test-writeuint.js deleted file mode 100644 index da0d79528..000000000 --- a/test/simple/test-writeuint.js +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -/* - * A battery of tests to help us read a series of uints - */ -var common = require('../common'); -var ASSERT = require('assert'); - -/* - * We need to check the following things: - * - We are correctly resolving big endian (doesn't mean anything for 8 bit) - * - Correctly resolving little endian (doesn't mean anything for 8 bit) - * - Correctly using the offsets - * - Correctly interpreting values that are beyond the signed range as unsigned - */ -function test8(clazz) { - var data = new clazz(4); - - data.writeUInt8(23, 0); - data.writeUInt8(23, 1); - data.writeUInt8(23, 2); - data.writeUInt8(23, 3); - ASSERT.equal(23, data[0]); - ASSERT.equal(23, data[1]); - ASSERT.equal(23, data[2]); - ASSERT.equal(23, data[3]); - - data.writeUInt8(23, 0); - data.writeUInt8(23, 1); - data.writeUInt8(23, 2); - data.writeUInt8(23, 3); - ASSERT.equal(23, data[0]); - ASSERT.equal(23, data[1]); - ASSERT.equal(23, data[2]); - ASSERT.equal(23, data[3]); - - data.writeUInt8(255, 0); - ASSERT.equal(255, data[0]); - - data.writeUInt8(255, 0); - ASSERT.equal(255, data[0]); -} - - -function test16(clazz) { - var value = 0x2343; - var data = new clazz(4); - - data.writeUInt16BE(value, 0); - ASSERT.equal(0x23, data[0]); - ASSERT.equal(0x43, data[1]); - - data.writeUInt16BE(value, 1); - ASSERT.equal(0x23, data[1]); - ASSERT.equal(0x43, data[2]); - - data.writeUInt16BE(value, 2); - ASSERT.equal(0x23, data[2]); - ASSERT.equal(0x43, data[3]); - - data.writeUInt16LE(value, 0); - ASSERT.equal(0x23, data[1]); - ASSERT.equal(0x43, data[0]); - - data.writeUInt16LE(value, 1); - ASSERT.equal(0x23, data[2]); - ASSERT.equal(0x43, data[1]); - - data.writeUInt16LE(value, 2); - ASSERT.equal(0x23, data[3]); - ASSERT.equal(0x43, data[2]); - - value = 0xff80; - data.writeUInt16LE(value, 0); - ASSERT.equal(0xff, data[1]); - ASSERT.equal(0x80, data[0]); - - data.writeUInt16BE(value, 0); - ASSERT.equal(0xff, data[0]); - ASSERT.equal(0x80, data[1]); -} - - -function test32(clazz) { - var data = new clazz(6); - var value = 0xe7f90a6d; - - data.writeUInt32BE(value, 0); - ASSERT.equal(0xe7, data[0]); - ASSERT.equal(0xf9, data[1]); - ASSERT.equal(0x0a, data[2]); - ASSERT.equal(0x6d, data[3]); - - data.writeUInt32BE(value, 1); - ASSERT.equal(0xe7, data[1]); - ASSERT.equal(0xf9, data[2]); - ASSERT.equal(0x0a, data[3]); - ASSERT.equal(0x6d, data[4]); - - data.writeUInt32BE(value, 2); - ASSERT.equal(0xe7, data[2]); - ASSERT.equal(0xf9, data[3]); - ASSERT.equal(0x0a, data[4]); - ASSERT.equal(0x6d, data[5]); - - data.writeUInt32LE(value, 0); - ASSERT.equal(0xe7, data[3]); - ASSERT.equal(0xf9, data[2]); - ASSERT.equal(0x0a, data[1]); - ASSERT.equal(0x6d, data[0]); - - data.writeUInt32LE(value, 1); - ASSERT.equal(0xe7, data[4]); - ASSERT.equal(0xf9, data[3]); - ASSERT.equal(0x0a, data[2]); - ASSERT.equal(0x6d, data[1]); - - data.writeUInt32LE(value, 2); - ASSERT.equal(0xe7, data[5]); - ASSERT.equal(0xf9, data[4]); - ASSERT.equal(0x0a, data[3]); - ASSERT.equal(0x6d, data[2]); -} - - -test8(Buffer); -test16(Buffer); -test32(Buffer); diff --git a/test/simple/test-zerolengthbufferbug.js b/test/simple/test-zerolengthbufferbug.js deleted file mode 100644 index 395e35baf..000000000 --- a/test/simple/test-zerolengthbufferbug.js +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Serving up a zero-length buffer should work. - -var common = require('../common'); -var assert = require('assert'); -var http = require('http'); - -var server = http.createServer(function(req, res) { - var buffer = new Buffer(0); - // FIXME: WTF gjslint want this? - res.writeHead(200, {'Content-Type': 'text/html', - 'Content-Length': buffer.length}); - res.end(buffer); -}); - -var gotResponse = false; -var resBodySize = 0; - -server.listen(common.PORT, function() { - http.get({ port: common.PORT }, function(res) { - gotResponse = true; - - res.on('data', function(d) { - resBodySize += d.length; - }); - - res.on('end', function(d) { - server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.ok(gotResponse); - assert.equal(0, resBodySize); -}); - diff --git a/test/simple/test-zlib-close-after-write.js b/test/simple/test-zlib-close-after-write.js deleted file mode 100644 index f0f176008..000000000 --- a/test/simple/test-zlib-close-after-write.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); - -var closed = false; - -zlib.gzip('hello', function(err, out) { - var unzip = zlib.createGunzip(); - unzip.write(out); - unzip.close(function() { - closed = true; - }); -}); - -process.on('exit', function() { - assert(closed); -}); diff --git a/test/simple/test-zlib-convenience-methods.js b/test/simple/test-zlib-convenience-methods.js deleted file mode 100644 index 88cf82f04..000000000 --- a/test/simple/test-zlib-convenience-methods.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test convenience methods with and without options supplied - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); - -var hadRun = 0; - -var expect = 'blahblahblahblahblahblah'; -var opts = { - level: 9, - chunkSize: 1024, -}; - -[ - ['gzip', 'gunzip'], - ['gzip', 'unzip'], - ['deflate', 'inflate'], - ['deflateRaw', 'inflateRaw'], -].forEach(function(method) { - - zlib[method[0]](expect, opts, function(err, result) { - zlib[method[1]](result, opts, function(err, result) { - assert.equal(result, expect, - 'Should get original string after ' + - method[0] + '/' + method[1] + ' with options.'); - hadRun++; - }); - }); - - zlib[method[0]](expect, function(err, result) { - zlib[method[1]](result, function(err, result) { - assert.equal(result, expect, - 'Should get original string after ' + - method[0] + '/' + method[1] + ' without options.'); - hadRun++; - }); - }); - - var result = zlib[method[0] + 'Sync'](expect, opts); - result = zlib[method[1] + 'Sync'](result, opts); - assert.equal(result, expect, - 'Should get original string after ' + - method[0] + '/' + method[1] + ' with options.'); - hadRun++; - - result = zlib[method[0] + 'Sync'](expect); - result = zlib[method[1] + 'Sync'](result); - assert.equal(result, expect, - 'Should get original string after ' + - method[0] + '/' + method[1] + ' without options.'); - hadRun++; - -}); - -process.on('exit', function() { - assert.equal(hadRun, 16, 'expect 16 compressions'); -}); diff --git a/test/simple/test-zlib-dictionary-fail.js b/test/simple/test-zlib-dictionary-fail.js deleted file mode 100644 index fd35a0192..000000000 --- a/test/simple/test-zlib-dictionary-fail.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); - -// Should raise an error, not trigger an assertion in src/node_zlib.cc -(function() { - var stream = zlib.createInflate(); - - stream.on('error', common.mustCall(function(err) { - assert(/Missing dictionary/.test(err.message)); - })); - - // String "test" encoded with dictionary "dict". - stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); -})(); - -// Should raise an error, not trigger an assertion in src/node_zlib.cc -(function() { - var stream = zlib.createInflate({ dictionary: Buffer('fail') }); - - stream.on('error', common.mustCall(function(err) { - assert(/Bad dictionary/.test(err.message)); - })); - - // String "test" encoded with dictionary "dict". - stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5])); -})(); diff --git a/test/simple/test-zlib-dictionary.js b/test/simple/test-zlib-dictionary.js deleted file mode 100644 index 58da810cc..000000000 --- a/test/simple/test-zlib-dictionary.js +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test compression/decompression with dictionary - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); -var path = require('path'); - -var spdyDict = new Buffer([ - 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-', - 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi', - 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser', - '-agent10010120020120220320420520630030130230330430530630740040140240340440', - '5406407408409410411412413414415416417500501502503504505accept-rangesageeta', - 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic', - 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran', - 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati', - 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo', - 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe', - 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic', - 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1', - '.1statusversionurl\0' -].join('')); - -var deflate = zlib.createDeflate({ dictionary: spdyDict }); - -var input = [ - 'HTTP/1.1 200 Ok', - 'Server: node.js', - 'Content-Length: 0', - '' -].join('\r\n'); - -var called = 0; - -// -// We'll use clean-new inflate stream each time -// and .reset() old dirty deflate one -// -function run(num) { - var inflate = zlib.createInflate({ dictionary: spdyDict }); - - if (num === 2) { - deflate.reset(); - deflate.removeAllListeners('data'); - } - - // Put data into deflate stream - deflate.on('data', function(chunk) { - inflate.write(chunk); - }); - - // Get data from inflate stream - var output = []; - inflate.on('data', function(chunk) { - output.push(chunk); - }); - inflate.on('end', function() { - called++; - - assert.equal(output.join(''), input); - - if (num < 2) run(num + 1); - }); - - deflate.write(input); - deflate.flush(function() { - inflate.end(); - }); -} -run(1); - -process.on('exit', function() { - assert.equal(called, 2); -}); diff --git a/test/simple/test-zlib-flush.js b/test/simple/test-zlib-flush.js deleted file mode 100644 index 0b189cecd..000000000 --- a/test/simple/test-zlib-flush.js +++ /dev/null @@ -1,35 +0,0 @@ -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); -var path = require('path'); -var fs = require('fs'); - -var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')), - chunkSize = 16, - opts = { level: 0 }, - deflater = zlib.createDeflate(opts); - -var chunk = file.slice(0, chunkSize), - expectedNone = new Buffer([0x78, 0x01]), - blkhdr = new Buffer([0x00, 0x10, 0x00, 0xef, 0xff]), - adler32 = new Buffer([0x00, 0x00, 0x00, 0xff, 0xff]), - expectedFull = Buffer.concat([blkhdr, chunk, adler32]), - actualNone, - actualFull; - -deflater.write(chunk, function() { - deflater.flush(zlib.Z_NO_FLUSH, function() { - actualNone = deflater.read(); - deflater.flush(function() { - var bufs = [], buf; - while (buf = deflater.read()) - bufs.push(buf); - actualFull = Buffer.concat(bufs); - }); - }); -}); - -process.once('exit', function() { - assert.deepEqual(actualNone, expectedNone); - assert.deepEqual(actualFull, expectedFull); -}); diff --git a/test/simple/test-zlib-from-gzip.js b/test/simple/test-zlib-from-gzip.js deleted file mode 100644 index 399354209..000000000 --- a/test/simple/test-zlib-from-gzip.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test unzipping a file that was created with a non-node gzip lib, -// piped in as fast as possible. - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); -var path = require('path'); - -var gunzip = zlib.createGunzip(); - -var fs = require('fs'); - -var fixture = path.resolve(common.fixturesDir, 'person.jpg.gz'); -var unzippedFixture = path.resolve(common.fixturesDir, 'person.jpg'); -var outputFile = path.resolve(common.tmpDir, 'person.jpg'); -var expect = fs.readFileSync(unzippedFixture); -var inp = fs.createReadStream(fixture); -var out = fs.createWriteStream(outputFile); - -inp.pipe(gunzip).pipe(out); -out.on('close', function() { - var actual = fs.readFileSync(outputFile); - assert.equal(actual.length, expect.length, 'length should match'); - for (var i = 0, l = actual.length; i < l; i++) { - assert.equal(actual[i], expect[i], 'byte[' + i + ']'); - } -}); diff --git a/test/simple/test-zlib-from-multiple-gzip-with-garbage.js b/test/simple/test-zlib-from-multiple-gzip-with-garbage.js deleted file mode 100644 index f6a0185e0..000000000 --- a/test/simple/test-zlib-from-multiple-gzip-with-garbage.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test unzipping a file that was created by concatenating multiple gzip -// streams. - -var common = require('../common'); -var assert = require('assert'); -var zlib = require('zlib'); - -var util = require('util'); - -var gzipBuffer = new Buffer(128); -var gzipOffset = 0; - -var stream1 = '123\n'; -var stream2 = '456\n'; -var stream3 = '789\n'; - -function gzipAppend(data) { - data.copy(gzipBuffer, gzipOffset); - gzipOffset += data.length; -} - -function writeGzipStream(text, cb) { - var gzip = zlib.createGzip(); - gzip.on('data', gzipAppend); - gzip.write(text, function() { - gzip.flush(function() { - gzip.end(function() { - cb(); - }); - }); - }); -} - -function writeGarbageStream(text, cb) { - gzipAppend(new Buffer(text)); - cb(); -} - -writeGzipStream(stream1, function() { - writeGzipStream(stream2, function() { - writeGarbageStream(stream3, function() { - var gunzip = zlib.createGunzip(); - var gunzippedData = new Buffer(2 * 1024); - var gunzippedOffset = 0; - gunzip.on('data', function (data) { - data.copy(gunzippedData, gunzippedOffset); - gunzippedOffset += data.length; - }); - gunzip.on('error', function() { - assert.equal(gunzippedData.toString('utf8', 0, gunzippedOffset), - stream1 + stream2); - }); - gunzip.on('end', function() { - assert.fail('end event not expected'); - }); - - gunzip.write(gzipBuffer.slice(0, gzipOffset), 'binary', function() { - gunzip.end(); - }); - }); - }); -}); diff --git a/test/simple/test-zlib-from-multiple-gzip.js b/test/simple/test-zlib-from-multiple-gzip.js deleted file mode 100644 index 6f4127a4d..000000000 --- a/test/simple/test-zlib-from-multiple-gzip.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test unzipping a file that was created by concatenating multiple gzip -// streams. - -var common = require('../common'); -var assert = require('assert'); -var zlib = require('zlib'); - -var util = require('util'); - -var gzipBuffer = new Buffer(128); -var gzipOffset = 0; - -var stream1 = '123\n'; -var stream2 = '456\n'; -var stream3 = '789\n'; - -function gzipAppend(data) { - data.copy(gzipBuffer, gzipOffset); - gzipOffset += data.length; -} - -function writeGzipStream(text, cb) { - var gzip = zlib.createGzip(); - gzip.on('data', gzipAppend); - gzip.write(text, function() { - gzip.flush(function() { - gzip.end(function() { - cb(); - }); - }); - }); -} - -writeGzipStream(stream1, function() { - writeGzipStream(stream2, function() { - writeGzipStream(stream3, function() { - var gunzip = zlib.createGunzip(); - var gunzippedData = new Buffer(2 * 1024); - var gunzippedOffset = 0; - gunzip.on('data', function (data) { - data.copy(gunzippedData, gunzippedOffset); - gunzippedOffset += data.length; - }); - gunzip.on('end', function() { - assert.equal(gunzippedData.toString('utf8', 0, gunzippedOffset), stream1 + stream2 + stream3); - }); - - gunzip.write(gzipBuffer.slice(0, gzipOffset), 'binary', function() { - gunzip.end(); - }); - }); - }); -}); diff --git a/test/simple/test-zlib-from-multiple-huge-gzip.js b/test/simple/test-zlib-from-multiple-huge-gzip.js deleted file mode 100644 index 5533aafeb..000000000 --- a/test/simple/test-zlib-from-multiple-huge-gzip.js +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test unzipping a file that was created by concatenating multiple gzip -// streams. - -var common = require('../common'); -var assert = require('assert'); -var zlib = require('zlib'); - -var util = require('util'); - -var HUGE = 64 * 1024; - -var originalBuffer = new Buffer(3 * HUGE); -var originalOffset = 0; - -var gzipBuffer = new Buffer(3 * HUGE); -var gzipOffset = 0; - -function getRandomLetter() { - return (Math.random() * (122 - 97)) + 97; -} - -function generateHugeStream() { - var buffer = new Buffer(HUGE); - for (var i = 0; i < HUGE; i++) - buffer.writeUInt8(getRandomLetter(), i); - - buffer.copy(originalBuffer, originalOffset); - originalOffset += HUGE; - - return buffer; -} - -function gzipAppend(data) { - data.copy(gzipBuffer, gzipOffset); - gzipOffset += data.length; -} - -function writeGzipStream(text, cb) { - var gzip = zlib.createGzip(); - gzip.on('data', gzipAppend); - gzip.write(text, function() { - gzip.flush(function() { - gzip.end(function() { - cb(); - }); - }); - }); -} - -writeGzipStream(generateHugeStream(), function() { - writeGzipStream(generateHugeStream(), function() { - writeGzipStream(generateHugeStream(), function() { - var gunzip = zlib.createGunzip(); - var gunzippedData = new Buffer(3 * HUGE); - var gunzippedOffset = 0; - gunzip.on('data', function (data) { - data.copy(gunzippedData, gunzippedOffset); - gunzippedOffset += data.length; - }); - gunzip.on('end', function() { - var gunzippedStr = gunzippedData.toString('utf8', 0, gunzippedOffset); - var originalStr = originalBuffer.toString('utf8', 0, 3 * HUGE); - - assert.equal(gunzippedStr, originalStr); - }); - - gunzip.write(gzipBuffer.slice(0, gzipOffset), 'binary', function() { - gunzip.end(); - }); - }); - }); -}); diff --git a/test/simple/test-zlib-from-string.js b/test/simple/test-zlib-from-string.js deleted file mode 100644 index 83bdeea83..000000000 --- a/test/simple/test-zlib-from-string.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test compressing and uncompressing a string with zlib - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); - -var inputString = 'ΩΩLorem ipsum dolor sit amet, consectetur adipiscing el' + - 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' + - 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' + - ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' + - 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' + - 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' + - 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' + - 'cu malesuada fermentum. Nunc sed. '; -var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' + - 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' + - 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' + - 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' + - 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' + - 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9'; -var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' + - '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' + - 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' + - 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' + - 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' + - 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' + - 'HnHNzRtagj5AQAA'; - -zlib.deflate(inputString, function(err, buffer) { - assert.equal(buffer.toString('base64'), expectedBase64Deflate, - 'deflate encoded string should match'); -}); - -zlib.gzip(inputString, function(err, buffer) { - // Can't actually guarantee that we'll get exactly the same - // deflated bytes when we compress a string, since the header - // depends on stuff other than the input string itself. - // However, decrypting it should definitely yield the same - // result that we're expecting, and this should match what we get - // from inflating the known valid deflate data. - zlib.gunzip(buffer, function(err, gunzipped) { - assert.equal(gunzipped.toString(), inputString, - 'Should get original string after gzip/gunzip'); - }); -}); - -var buffer = new Buffer(expectedBase64Deflate, 'base64'); -zlib.unzip(buffer, function(err, buffer) { - assert.equal(buffer.toString(), inputString, - 'decoded inflated string should match'); -}); - -buffer = new Buffer(expectedBase64Gzip, 'base64'); -zlib.unzip(buffer, function(err, buffer) { - assert.equal(buffer.toString(), inputString, - 'decoded gunzipped string should match'); -}); diff --git a/test/simple/test-zlib-invalid-input.js b/test/simple/test-zlib-invalid-input.js deleted file mode 100644 index c3d8b5b47..000000000 --- a/test/simple/test-zlib-invalid-input.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// test uncompressing invalid input - -var common = require('../common.js'), - assert = require('assert'), - zlib = require('zlib'); - -var nonStringInputs = [1, true, {a: 1}, ['a']]; - -console.error('Doing the non-strings'); -nonStringInputs.forEach(function(input) { - // zlib.gunzip should not throw an error when called with bad input. - assert.doesNotThrow(function() { - zlib.gunzip(input, function(err, buffer) { - // zlib.gunzip should pass the error to the callback. - assert.ok(err); - }); - }); -}); - -console.error('Doing the unzips'); -// zlib.Unzip classes need to get valid data, or else they'll throw. -var unzips = [ zlib.Unzip(), - zlib.Gunzip(), - zlib.Inflate(), - zlib.InflateRaw() ]; -var hadError = []; -unzips.forEach(function (uz, i) { - console.error('Error for '+uz.constructor.name); - uz.on('error', function(er) { - console.error('Error event', er); - hadError[i] = true; - }); - - uz.on('end', function(er) { - throw new Error('end event should not be emitted '+uz.constructor.name); - }); - - // this will trigger error event - uz.write('this is not valid compressed data.'); -}); - -process.on('exit', function() { - assert.deepEqual(hadError, [true, true, true, true], 'expect 4 errors'); -}); diff --git a/test/simple/test-zlib-params.js b/test/simple/test-zlib-params.js deleted file mode 100644 index 006f1ea8e..000000000 --- a/test/simple/test-zlib-params.js +++ /dev/null @@ -1,33 +0,0 @@ -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); -var path = require('path'); -var fs = require('fs'); - -var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')), - chunkSize = 24 * 1024, - opts = { level: 9, strategy: zlib.Z_DEFAULT_STRATEGY }, - deflater = zlib.createDeflate(opts); - -var chunk1 = file.slice(0, chunkSize), - chunk2 = file.slice(chunkSize), - blkhdr = new Buffer([0x00, 0x48, 0x82, 0xb7, 0x7d]), - expected = Buffer.concat([blkhdr, chunk2]), - actual; - -deflater.write(chunk1, function() { - deflater.params(0, zlib.Z_DEFAULT_STRATEGY, function() { - while (deflater.read()); - deflater.end(chunk2, function() { - var bufs = [], buf; - while (buf = deflater.read()) - bufs.push(buf); - actual = Buffer.concat(bufs); - }); - }); - while (deflater.read()); -}); - -process.once('exit', function() { - assert.deepEqual(actual, expected); -}); diff --git a/test/simple/test-zlib-random-byte-pipes.js b/test/simple/test-zlib-random-byte-pipes.js deleted file mode 100644 index fc1db1cbb..000000000 --- a/test/simple/test-zlib-random-byte-pipes.js +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var crypto = require('crypto'); -var stream = require('stream'); -var Stream = stream.Stream; -var util = require('util'); -var assert = require('assert'); -var zlib = require('zlib'); - - - -// emit random bytes, and keep a shasum -function RandomReadStream(opt) { - Stream.call(this); - - this.readable = true; - this._paused = false; - this._processing = false; - - this._hasher = crypto.createHash('sha1'); - opt = opt || {}; - - // base block size. - opt.block = opt.block || 256 * 1024; - - // total number of bytes to emit - opt.total = opt.total || 256 * 1024 * 1024; - this._remaining = opt.total; - - // how variable to make the block sizes - opt.jitter = opt.jitter || 1024; - - this._opt = opt; - - this._process = this._process.bind(this); - - process.nextTick(this._process); -} - -util.inherits(RandomReadStream, Stream); - -RandomReadStream.prototype.pause = function() { - this._paused = true; - this.emit('pause'); -}; - -RandomReadStream.prototype.resume = function() { - // console.error("rrs resume"); - this._paused = false; - this.emit('resume'); - this._process(); -}; - -RandomReadStream.prototype._process = function() { - if (this._processing) return; - if (this._paused) return; - - this._processing = true; - - if (!this._remaining) { - this._hash = this._hasher.digest('hex').toLowerCase().trim(); - this._processing = false; - - this.emit('end'); - return; - } - - // figure out how many bytes to output - // if finished, then just emit end. - var block = this._opt.block; - var jitter = this._opt.jitter; - if (jitter) { - block += Math.ceil(Math.random() * jitter - (jitter / 2)); - } - block = Math.min(block, this._remaining); - var buf = new Buffer(block); - for (var i = 0; i < block; i++) { - buf[i] = Math.random() * 256; - } - - this._hasher.update(buf); - - this._remaining -= block; - - console.error('block=%d\nremain=%d\n', block, this._remaining); - this._processing = false; - - this.emit('data', buf); - process.nextTick(this._process); -}; - - -// a filter that just verifies a shasum -function HashStream() { - Stream.call(this); - - this.readable = this.writable = true; - this._hasher = crypto.createHash('sha1'); -} - -util.inherits(HashStream, Stream); - -HashStream.prototype.write = function(c) { - // Simulate the way that an fs.ReadStream returns false - // on *every* write like a jerk, only to resume a - // moment later. - this._hasher.update(c); - process.nextTick(this.resume.bind(this)); - return false; -}; - -HashStream.prototype.resume = function() { - this.emit('resume'); - process.nextTick(this.emit.bind(this, 'drain')); -}; - -HashStream.prototype.end = function(c) { - if (c) { - this.write(c); - } - this._hash = this._hasher.digest('hex').toLowerCase().trim(); - this.emit('data', this._hash); - this.emit('end'); -}; - - - - -var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); -var out = new HashStream(); -var gzip = zlib.createGzip(); -var gunz = zlib.createGunzip(); - -inp.pipe(gzip).pipe(gunz).pipe(out); - -inp.on('data', function(c) { - console.error('inp data', c.length); -}); - -gzip.on('data', function(c) { - console.error('gzip data', c.length); -}); - -gunz.on('data', function(c) { - console.error('gunz data', c.length); -}); - -out.on('data', function(c) { - console.error('out data', c.length); -}); - -var didSomething = false; -out.on('data', function(c) { - didSomething = true; - console.error('hash=%s', c); - assert.equal(c, inp._hash, 'hashes should match'); -}); - -process.on('exit', function() { - assert(didSomething, 'should have done something'); -}); diff --git a/test/simple/test-zlib-write-after-close.js b/test/simple/test-zlib-write-after-close.js deleted file mode 100644 index d3f3d4e6b..000000000 --- a/test/simple/test-zlib-write-after-close.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); - -var closed = false; - -zlib.gzip('hello', function(err, out) { - var unzip = zlib.createGunzip(); - unzip.close(function() { - closed = true; - }); - assert.throws(function() { - unzip.write(out); - }); -}); - -process.on('exit', function() { - assert(closed); -}); diff --git a/test/simple/test-zlib-write-after-flush.js b/test/simple/test-zlib-write-after-flush.js deleted file mode 100644 index e13871ecb..000000000 --- a/test/simple/test-zlib-write-after-flush.js +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); -var zlib = require('zlib'); -var fs = require('fs'); - -var gzip = zlib.createGzip(); -var gunz = zlib.createUnzip(); - -gzip.pipe(gunz); - -var output = ''; -var input = 'A line of data\n'; -gunz.setEncoding('utf8'); -gunz.on('data', function(c) { - output += c; -}); - -process.on('exit', function() { - assert.equal(output, input); - - // Make sure that the flush flag was set back to normal - assert.equal(gzip._flushFlag, zlib.Z_NO_FLUSH); - - console.log('ok'); -}); - -// make sure that flush/write doesn't trigger an assert failure -gzip.flush(); write(); -function write() { - gzip.write(input); - gzip.end(); - gunz.read(0); -} diff --git a/test/simple/test-zlib-zero-byte.js b/test/simple/test-zlib-zero-byte.js deleted file mode 100644 index 31ac86bd6..000000000 --- a/test/simple/test-zlib-zero-byte.js +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common'); -var assert = require('assert'); - -var zlib = require('zlib'); -var gz = zlib.Gzip() -var emptyBuffer = new Buffer(0); -var received = 0; -gz.on('data', function(c) { - received += c.length; -}); -var ended = false; -gz.on('end', function() { - ended = true; -}); -var finished = false; -gz.on('finish', function() { - finished = true; -}); -gz.write(emptyBuffer); -gz.end(); - -process.on('exit', function() { - assert.equal(received, 20); - assert(ended); - assert(finished); - console.log('ok'); -}); diff --git a/test/simple/test-zlib.js b/test/simple/test-zlib.js deleted file mode 100644 index b9267525e..000000000 --- a/test/simple/test-zlib.js +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var common = require('../common.js'); -var assert = require('assert'); -var zlib = require('zlib'); -var path = require('path'); - -var zlibPairs = - [[zlib.Deflate, zlib.Inflate], - [zlib.Gzip, zlib.Gunzip], - [zlib.Deflate, zlib.Unzip], - [zlib.Gzip, zlib.Unzip], - [zlib.DeflateRaw, zlib.InflateRaw]]; - -// how fast to trickle through the slowstream -var trickle = [128, 1024, 1024 * 1024]; - -// tunable options for zlib classes. - -// several different chunk sizes -var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; - -// this is every possible value. -var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; -var windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; -var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; -var strategy = [0, 1, 2, 3, 4]; - -// it's nice in theory to test every combination, but it -// takes WAY too long. Maybe a pummel test could do this? -if (!process.env.PUMMEL) { - trickle = [1024]; - chunkSize = [1024 * 16]; - level = [6]; - memLevel = [8]; - windowBits = [15]; - strategy = [0]; -} - -var fs = require('fs'); - -var testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; - -if (process.env.FAST) { - zlibPairs = [[zlib.Gzip, zlib.Unzip]]; - var testFiles = ['person.jpg']; -} - -var tests = {}; -testFiles.forEach(function(file) { - tests[file] = fs.readFileSync(path.resolve(common.fixturesDir, file)); -}); - -var util = require('util'); -var stream = require('stream'); - - -// stream that saves everything -function BufferStream() { - this.chunks = []; - this.length = 0; - this.writable = true; - this.readable = true; -} - -util.inherits(BufferStream, stream.Stream); - -BufferStream.prototype.write = function(c) { - this.chunks.push(c); - this.length += c.length; - return true; -}; - -BufferStream.prototype.end = function(c) { - if (c) this.write(c); - // flatten - var buf = new Buffer(this.length); - var i = 0; - this.chunks.forEach(function(c) { - c.copy(buf, i); - i += c.length; - }); - this.emit('data', buf); - this.emit('end'); - return true; -}; - - -function SlowStream(trickle) { - this.trickle = trickle; - this.offset = 0; - this.readable = this.writable = true; -} - -util.inherits(SlowStream, stream.Stream); - -SlowStream.prototype.write = function() { - throw new Error('not implemented, just call ss.end(chunk)'); -}; - -SlowStream.prototype.pause = function() { - this.paused = true; - this.emit('pause'); -}; - -SlowStream.prototype.resume = function() { - var self = this; - if (self.ended) return; - self.emit('resume'); - if (!self.chunk) return; - self.paused = false; - emit(); - function emit() { - if (self.paused) return; - if (self.offset >= self.length) { - self.ended = true; - return self.emit('end'); - } - var end = Math.min(self.offset + self.trickle, self.length); - var c = self.chunk.slice(self.offset, end); - self.offset += c.length; - self.emit('data', c); - process.nextTick(emit); - } -}; - -SlowStream.prototype.end = function(chunk) { - // walk over the chunk in blocks. - var self = this; - self.chunk = chunk; - self.length = chunk.length; - self.resume(); - return self.ended; -}; - - - -// for each of the files, make sure that compressing and -// decompressing results in the same data, for every combination -// of the options set above. -var failures = 0; -var total = 0; -var done = 0; - -Object.keys(tests).forEach(function(file) { - var test = tests[file]; - chunkSize.forEach(function(chunkSize) { - trickle.forEach(function(trickle) { - windowBits.forEach(function(windowBits) { - level.forEach(function(level) { - memLevel.forEach(function(memLevel) { - strategy.forEach(function(strategy) { - zlibPairs.forEach(function(pair) { - var Def = pair[0]; - var Inf = pair[1]; - var opts = { level: level, - windowBits: windowBits, - memLevel: memLevel, - strategy: strategy }; - - total++; - - var def = new Def(opts); - var inf = new Inf(opts); - var ss = new SlowStream(trickle); - var buf = new BufferStream(); - - // verify that the same exact buffer comes out the other end. - buf.on('data', function(c) { - var msg = file + ' ' + - chunkSize + ' ' + - JSON.stringify(opts) + ' ' + - Def.name + ' -> ' + Inf.name; - var ok = true; - var testNum = ++done; - for (var i = 0; i < Math.max(c.length, test.length); i++) { - if (c[i] !== test[i]) { - ok = false; - failures++; - break; - } - } - if (ok) { - console.log('ok ' + (testNum) + ' ' + msg); - } else { - console.log('not ok ' + (testNum) + ' ' + msg); - console.log(' ...'); - console.log(' testfile: ' + file); - console.log(' type: ' + Def.name + ' -> ' + Inf.name); - console.log(' position: ' + i); - console.log(' options: ' + JSON.stringify(opts)); - console.log(' expect: ' + test[i]); - console.log(' actual: ' + c[i]); - console.log(' chunkSize: ' + chunkSize); - console.log(' ---'); - } - }); - - // the magic happens here. - ss.pipe(def).pipe(inf).pipe(buf); - ss.end(test); - }); - }); }); }); }); }); }); // sad stallman is sad. -}); - -process.on('exit', function(code) { - console.log('1..' + done); - assert.equal(done, total, (total - done) + ' tests left unfinished'); - assert.ok(!failures, 'some test failures'); -}); diff --git a/test/simple/testcfg.py b/test/simple/testcfg.py deleted file mode 100644 index 3d9b6296b..000000000 --- a/test/simple/testcfg.py +++ /dev/null @@ -1,6 +0,0 @@ -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) -import testpy - -def GetConfiguration(context, root): - return testpy.SimpleTestConfiguration(context, root, 'simple') diff --git a/tools/test.py b/tools/test.py index 94792e2af..cb60fbda1 100755 --- a/tools/test.py +++ b/tools/test.py @@ -1317,7 +1317,8 @@ def GetSpecialCommandProcessor(value): BUILT_IN_TESTS = [ - 'simple', + 'sequential', + 'parallel', 'pummel', 'message', 'internet', diff --git a/vcbuild.bat b/vcbuild.bat index 90cfc5469..ab46819eb 100644 --- a/vcbuild.bat +++ b/vcbuild.bat @@ -163,10 +163,10 @@ if "%test%"=="" goto exit if "%config%"=="Debug" set test_args=--mode=debug if "%config%"=="Release" set test_args=--mode=release -if "%test%"=="test" set test_args=%test_args% simple message +if "%test%"=="test" set test_args=%test_args% sequential parallel message if "%test%"=="test-internet" set test_args=%test_args% internet if "%test%"=="test-pummel" set test_args=%test_args% pummel -if "%test%"=="test-simple" set test_args=%test_args% simple +if "%test%"=="test-simple" set test_args=%test_args% sequential parallel if "%test%"=="test-message" set test_args=%test_args% message if "%test%"=="test-gc" set test_args=%test_args% gc if "%test%"=="test-all" set test_args=%test_args%