Browse Source

GJSLint all tests, only 3 long lines left in test-url.js

test/simple/test-url.js:31:(0110) Line too long (82 characters).
test/simple/test-url.js:39:(0110) Line too long (85 characters).
test/simple/test-url.js:40:(0110) Line too long (92 characters).
v0.7.4-release
Oleg Efimov 14 years ago
committed by Ryan Dahl
parent
commit
093dfaf801
  1. 5
      test/common.js
  2. 37
      test/disabled/test-cat.js
  3. 84
      test/disabled/test-dns.js
  4. 5
      test/disabled/test-eio-race3.js
  5. 23
      test/disabled/test-fs-sendfile.js
  6. 38
      test/disabled/test-http-big-proxy-responses.js
  7. 25
      test/disabled/test-http-head-request.js
  8. 17
      test/disabled/test-http-stress.js
  9. 123
      test/disabled/test-http-tls.js
  10. 6
      test/disabled/test-idle-watcher.js
  11. 31
      test/disabled/test-net-fd-passing.js
  12. 91
      test/disabled/test-net-tls-pummel.js
  13. 84
      test/disabled/test-net-tls.js
  14. 14
      test/disabled/test-process-title.js
  15. 14
      test/disabled/test-readline.js
  16. 18
      test/disabled/test-remote-module-loading.js
  17. 4
      test/disabled/test-setuidgid.js
  18. 28
      test/disabled/test-tls-server.js
  19. 47
      test/disabled/tls_client.js
  20. 43
      test/disabled/tls_server.js
  21. 2
      test/fixtures/echo.js
  22. 2
      test/fixtures/print-chars-from-buffer.js
  23. 4
      test/message/undefined_reference_in_new_context.js
  24. 2
      test/pummel/test-child-process-spawn-loop.js
  25. 2
      test/pummel/test-http-client-reconnect-bug.js
  26. 2
      test/pummel/test-keep-alive.js
  27. 2
      test/pummel/test-net-many-clients.js
  28. 2
      test/pummel/test-net-pause.js
  29. 2
      test/pummel/test-net-pingpong-delay.js
  30. 2
      test/pummel/test-net-pingpong.js
  31. 2
      test/pummel/test-net-throttle.js
  32. 7
      test/pummel/test-net-timeout.js
  33. 14
      test/pummel/test-timers.js
  34. 2
      test/pummel/test-watch-file.js
  35. 30
      test/simple/test-http-1.0.js
  36. 9
      test/simple/test-http-304.js
  37. 10
      test/simple/test-http-allow-req-after-204-res.js
  38. 28
      test/simple/test-http-blank-header.js
  39. 28
      test/simple/test-http-buffer-sanity.js
  40. 29
      test/simple/test-http-cat.js
  41. 19
      test/simple/test-http-chunked.js
  42. 12
      test/simple/test-http-client-parse-error.js
  43. 65
      test/simple/test-http-client-race-2.js
  44. 43
      test/simple/test-http-client-race.js
  45. 24
      test/simple/test-http-client-upload.js
  46. 11
      test/simple/test-http-contentLength0.js
  47. 19
      test/simple/test-http-curl-chunk-problem.js
  48. 8
      test/simple/test-http-eof-on-connect.js
  49. 18
      test/simple/test-http-exceptions.js
  50. 52
      test/simple/test-http-expect-continue.js
  51. 38
      test/simple/test-http-full-response.js
  52. 16
      test/simple/test-http-head-request.js
  53. 8
      test/simple/test-http-head-response-has-no-body.js
  54. 34
      test/simple/test-http-keep-alive-close-on-header.js
  55. 35
      test/simple/test-http-keep-alive.js
  56. 18
      test/simple/test-http-malformed-request.js
  57. 32
      test/simple/test-http-parser.js
  58. 62
      test/simple/test-http-proxy.js
  59. 5
      test/simple/test-http-server-multiheaders.js
  60. 66
      test/simple/test-http-server.js
  61. 18
      test/simple/test-http-set-cookies.js
  62. 17
      test/simple/test-http-set-timeout.js
  63. 53
      test/simple/test-http-set-trailers.js
  64. 8
      test/simple/test-http-upgrade-client.js
  65. 8
      test/simple/test-http-upgrade-client2.js
  66. 125
      test/simple/test-http-upgrade-server.js
  67. 28
      test/simple/test-http-upgrade-server2.js
  68. 32
      test/simple/test-http-wget.js
  69. 20
      test/simple/test-http-write-empty-string.js
  70. 68
      test/simple/test-http.js
  71. 114
      test/simple/test-path.js
  72. 615
      test/simple/test-url.js

5
test/common.js

@ -1,4 +1,5 @@
var path = require('path'); var path = require('path');
var assert = require('assert');
exports.testDir = path.dirname(__filename); exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures'); exports.fixturesDir = path.join(exports.testDir, 'fixtures');
@ -6,8 +7,6 @@ exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp'); exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = 12346; exports.PORT = 12346;
exports.assert = require('assert');
var util = require('util'); var util = require('util');
for (var i in util) exports[i] = util[i]; for (var i in util) exports[i] = util[i];
//for (var i in exports) global[i] = exports[i]; //for (var i in exports) global[i] = exports[i];
@ -52,7 +51,7 @@ process.on('exit', function() {
if (!found) { if (!found) {
console.error('Unknown global: %s', x); console.error('Unknown global: %s', x);
exports.assert.ok(false); assert.ok(false, 'Unknown global founded');
} }
} }
}); });

37
test/disabled/test-cat.js

@ -1,14 +1,15 @@
require("../common.js"); var common = require('../common.js');
http = require("/http.js"); var assert = require('assert');
var http = require('http');
console.log("hello world"); console.log('hello world');
var body = "exports.A = function() { return 'A';}"; var body = 'exports.A = function() { return "A";}';
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
console.log("req?"); console.log('req?');
res.sendHeader(200, { res.sendHeader(200, {
"Content-Length": body.length, 'Content-Length': body.length,
"Content-Type": "text/plain" 'Content-Type': 'text/plain'
}); });
res.sendBody(body); res.sendBody(body);
res.finish(); res.finish();
@ -18,34 +19,34 @@ server.listen(common.PORT);
var errors = 0; var errors = 0;
var successes = 0; var successes = 0;
var promise = process.cat("http://localhost:"+common.PORT, "utf8"); var promise = process.cat('http://localhost:' + common.PORT, 'utf8');
promise.addCallback(function (content) { promise.addCallback(function(content) {
assert.equal(body, content); assert.equal(body, content);
server.close(); server.close();
successes += 1; successes += 1;
}); });
promise.addErrback(function () { promise.addErrback(function() {
errors += 1; errors += 1;
}); });
var dirname = process.path.dirname(__filename); var dirname = process.path.dirname(__filename);
var fixtures = process.path.join(dirname, "fixtures"); var fixtures = process.path.join(dirname, 'fixtures');
var x = process.path.join(fixtures, "x.txt"); var x = process.path.join(fixtures, 'x.txt');
promise = process.cat(x, "utf8"); promise = process.cat(x, 'utf8');
promise.addCallback(function (content) { promise.addCallback(function(content) {
assert.equal("xyz", content.replace(/[\r\n]/, '')); assert.equal('xyz', content.replace(/[\r\n]/, ''));
successes += 1; successes += 1;
}); });
promise.addErrback(function () { promise.addErrback(function() {
errors += 1; errors += 1;
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(2, successes); assert.equal(2, successes);
assert.equal(0, errors); assert.equal(0, errors);
}); });

84
test/disabled/test-dns.js

@ -1,16 +1,16 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var dns = require("dns"), var dns = require('dns'),
child_process = require("child_process"); child_process = require('child_process');
// Try resolution without callback // Try resolution without callback
assert.throws(function () { assert.throws(function() {
dns.resolve('google.com', 'A'); dns.resolve('google.com', 'A');
}); });
assert.throws(function () { assert.throws(function() {
dns.resolve('127.0.0.1', 'PTR'); dns.resolve('127.0.0.1', 'PTR');
}); });
@ -21,7 +21,7 @@ var hosts = ['example.com',
'google.com', // MX, multiple A records 'google.com', // MX, multiple A records
'_xmpp-client._tcp.google.com', // SRV '_xmpp-client._tcp.google.com', // SRV
'oakalynhall.co.uk' // Multiple PTR replies 'oakalynhall.co.uk' // Multiple PTR replies
]; ];
var records = ['A', 'AAAA', 'MX', 'TXT', 'SRV']; var records = ['A', 'AAAA', 'MX', 'TXT', 'SRV'];
@ -30,10 +30,10 @@ while (i--) {
var j = records.length; var j = records.length;
while (j--) { while (j--) {
var hostCmd = "dig -t " + records[j] + " " + hosts[i] + var hostCmd = 'dig -t ' + records[j] + ' ' + hosts[i] +
"| grep '^" + hosts[i] + "\\.\\W.*IN.*" + records[j] + "'" + '| grep "^' + hosts[i] + '\\.\\W.*IN.*' + records[j] + '"' +
"| sed -E 's/[[:space:]]+/ /g' | cut -d ' ' -f 5- " + '| sed -E "s/[[:space:]]+/ /g" | cut -d " " -f 5- ' +
"| sed -e 's/\\.$//'"; '| sed -e "s/\\.$//"';
child_process.exec(hostCmd, checkDnsRecord(hosts[i], records[j])); child_process.exec(hostCmd, checkDnsRecord(hosts[i], records[j]));
} }
} }
@ -53,43 +53,43 @@ function checkDnsRecord(host, record) {
myRecord = record; myRecord = record;
return function(err, stdout) { return function(err, stdout) {
var expected = []; var expected = [];
if(stdout.length) if (stdout.length)
expected = stdout.substr(0, stdout.length - 1).split("\n"); expected = stdout.substr(0, stdout.length - 1).split('\n');
switch (myRecord) { switch (myRecord) {
case "A": case 'A':
case "AAAA": case 'AAAA':
dns.resolve(myHost, myRecord, function (error, result, ttl, cname) { dns.resolve(myHost, myRecord, function(error, result, ttl, cname) {
if(error) result = []; if (error) result = [];
cmpResults(expected, result, ttl, cname); cmpResults(expected, result, ttl, cname);
// do reverse lookup check // do reverse lookup check
var ll = result.length; var ll = result.length;
while (ll--) { while (ll--) {
var ip = result[ll]; var ip = result[ll];
var reverseCmd = "host " + ip + var reverseCmd = 'host ' + ip +
"| cut -d \" \" -f 5-" + '| cut -d " " -f 5-' +
"| sed -e 's/\\.$//'"; '| sed -e "s/\\.$//"';
child_process.exec(reverseCmd, checkReverse(ip)); child_process.exec(reverseCmd, checkReverse(ip));
} }
}); });
break; break;
case "MX": case 'MX':
dns.resolve(myHost, myRecord, function (error, result, ttl, cname) { dns.resolve(myHost, myRecord, function(error, result, ttl, cname) {
if(error) result = []; if (error) result = [];
var strResult = []; var strResult = [];
var ll = result.length; var ll = result.length;
while (ll--) { while (ll--) {
strResult.push(result[ll].priority + " " + result[ll].exchange); strResult.push(result[ll].priority + ' ' + result[ll].exchange);
} }
cmpResults(expected, strResult, ttl, cname); cmpResults(expected, strResult, ttl, cname);
}); });
break; break;
case "TXT": case 'TXT':
dns.resolve(myHost, myRecord, function (error, result, ttl, cname) { dns.resolve(myHost, myRecord, function(error, result, ttl, cname) {
if(error) result = []; if (error) result = [];
var strResult = []; var strResult = [];
var ll = result.length; var ll = result.length;
@ -99,16 +99,16 @@ function checkDnsRecord(host, record) {
cmpResults(expected, strResult, ttl, cname); cmpResults(expected, strResult, ttl, cname);
}); });
break; break;
case "SRV": case 'SRV':
dns.resolve(myHost, myRecord, function (error, result, ttl, cname) { dns.resolve(myHost, myRecord, function(error, result, ttl, cname) {
if(error) result = []; if (error) result = [];
var strResult = []; var strResult = [];
var ll = result.length; var ll = result.length;
while (ll--) { while (ll--) {
strResult.push(result[ll].priority + " " + strResult.push(result[ll].priority + ' ' +
result[ll].weight + " " + result[ll].weight + ' ' +
result[ll].port + " " + result[ll].port + ' ' +
result[ll].name); result[ll].name);
} }
cmpResults(expected, strResult, ttl, cname); cmpResults(expected, strResult, ttl, cname);
@ -121,11 +121,11 @@ function checkDnsRecord(host, record) {
function checkReverse(ip) { function checkReverse(ip) {
var myIp = ip; var myIp = ip;
return function (errr, stdout) { return function(errr, stdout) {
var expected = stdout.substr(0, stdout.length - 1).split("\n"); var expected = stdout.substr(0, stdout.length - 1).split('\n');
reversing = dns.reverse(myIp, function (error, domains, ttl, cname) { var reversing = dns.reverse(myIp, function(error, domains, ttl, cname) {
if(error) domains = []; if (error) domains = [];
cmpResults(expected, domains, ttl, cname); cmpResults(expected, domains, ttl, cname);
}); });
} }
@ -133,19 +133,23 @@ function checkReverse(ip) {
function cmpResults(expected, result, ttl, cname) { function cmpResults(expected, result, ttl, cname) {
if (expected.length != result.length) { if (expected.length != result.length) {
if (expected.length == 1 && expected[0] == '3(NXDOMAIN)' && result.length == 0) { if (expected.length == 1 &&
expected[0] == '3(NXDOMAIN)' &&
result.length == 0) {
// it's ok, dig returns NXDOMAIN, while dns module returns nothing // it's ok, dig returns NXDOMAIN, while dns module returns nothing
} else { } else {
console.log('---WARNING---\nexpected ' + expected + '\nresult ' + result + '\n-------------'); console.log('---WARNING---\nexpected ' + expected +
'\nresult ' + result + '\n-------------');
} }
return; return;
} }
expected.sort(); expected.sort();
result.sort(); result.sort();
ll = expected.length; var ll = expected.length;
while (ll--) { while (ll--) {
assert.equal(result[ll], expected[ll]); assert.equal(result[ll], expected[ll]);
console.log("Result " + result[ll] + " was equal to expected " + expected[ll]); console.log('Result ' + result[ll] +
' was equal to expected ' + expected[ll]);
} }
} }

5
test/disabled/test-eio-race3.js

@ -1,18 +1,17 @@
/* XXX Can this test be modified to not call the now-removed wait()? */ /* XXX Can this test be modified to not call the now-removed wait()? */
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
console.log('first stat ...'); console.log('first stat ...');
fs.stat(__filename) fs.stat(__filename)
.addCallback( function(stats) { .addCallback(function(stats) {
console.log('second stat ...'); console.log('second stat ...');
fs.stat(__filename) fs.stat(__filename)
.timeout(1000) .timeout(1000)
.wait(); .wait();
console.log('test passed'); console.log('test passed');
}) })
.addErrback(function() { .addErrback(function() {

23
test/disabled/test-fs-sendfile.js

@ -1,13 +1,13 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
tcp = require("tcp"); var net = require('net');
util = require("util"); var util = require('util');
var x = path.join(common.fixturesDir, "x.txt"); var x = path.join(common.fixturesDir, 'x.txt');
var expected = "xyz"; var expected = 'xyz';
var server = tcp.createServer(function (socket) { var server = net.createServer(function(socket) {
socket.addListener("receive", function (data) { socket.addListener('receive', function(data) {
found = data; found = data;
client.close(); client.close();
socket.close(); socket.close();
@ -17,10 +17,11 @@ var server = tcp.createServer(function (socket) {
}); });
server.listen(common.PORT); server.listen(common.PORT);
var client = tcp.createConnection(common.PORT); var client = net.createConnection(common.PORT);
client.addListener("connect", function () { client.addListener('connect', function() {
fs.open(x, 'r').addCallback(function (fd) { fs.open(x, 'r').addCallback(function(fd) {
fs.sendfile(client.fd, fd, 0, expected.length).addCallback(function (size) { fs.sendfile(client.fd, fd, 0, expected.length)
.addCallback(function(size) {
assert.equal(expected.length, size); assert.equal(expected.length, size);
}); });
}); });

38
test/disabled/test-http-big-proxy-responses.js

@ -1,18 +1,18 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var util = require("util"), var util = require('util'),
fs = require("fs"), fs = require('fs'),
http = require("http"), http = require('http'),
url = require("url"); url = require('url');
var chunk = '01234567890123456789'; var chunk = '01234567890123456789';
// Produce a very large response. // Produce a very large response.
var chargen = http.createServer(function (req, res) { var chargen = http.createServer(function(req, res) {
var len = parseInt(req.headers['x-len'], 10); var len = parseInt(req.headers['x-len'], 10);
assert.ok(len > 0); assert.ok(len > 0);
res.writeHead(200, {"transfer-encoding":"chunked"}); res.writeHead(200, {'transfer-encoding': 'chunked'});
for (var i=0; i<len; i++) { for (var i = 0; i < len; i++) {
if (i % 1000 == 0) common.print(','); if (i % 1000 == 0) common.print(',');
res.write(chunk); res.write(chunk);
} }
@ -21,7 +21,7 @@ var chargen = http.createServer(function (req, res) {
chargen.listen(9000, ready); chargen.listen(9000, ready);
// Proxy to the chargen server. // Proxy to the chargen server.
var proxy = http.createServer(function (req, res) { var proxy = http.createServer(function(req, res) {
var c = http.createClient(9000, 'localhost'); var c = http.createClient(9000, 'localhost');
var len = parseInt(req.headers['x-len'], 10); var len = parseInt(req.headers['x-len'], 10);
@ -30,7 +30,7 @@ var proxy = http.createServer(function (req, res) {
var sent = 0; var sent = 0;
c.addListener('error', function (e) { c.addListener('error', function(e) {
console.log('proxy client error. sent ' + sent); console.log('proxy client error. sent ' + sent);
throw e; throw e;
}); });
@ -45,7 +45,7 @@ var proxy = http.createServer(function (req, res) {
if (count++ % 1000 == 0) common.print('.'); if (count++ % 1000 == 0) common.print('.');
res.write(d); res.write(d);
sent += d.length; sent += d.length;
assert.ok(sent <= (len*chunk.length)); assert.ok(sent <= (len * chunk.length));
}); });
proxy_res.addListener('end', function() { proxy_res.addListener('end', function() {
@ -64,7 +64,7 @@ function call_chargen(list) {
if (list.length > 0) { if (list.length > 0) {
var len = list.shift(); var len = list.shift();
common.debug("calling chargen for " + len + " chunks."); common.debug('calling chargen for ' + len + ' chunks.');
var recved = 0; var recved = 0;
@ -74,12 +74,12 @@ function call_chargen(list) {
res.addListener('data', function(d) { res.addListener('data', function(d) {
recved += d.length; recved += d.length;
assert.ok(recved <= (len*chunk.length)); assert.ok(recved <= (len * chunk.length));
}); });
res.addListener('end', function() { res.addListener('end', function() {
assert.ok(recved <= (len*chunk.length)); assert.ok(recved <= (len * chunk.length));
common.debug("end for " + len + " chunks."); common.debug('end for ' + len + ' chunks.');
call_chargen(list); call_chargen(list);
}); });
@ -87,7 +87,7 @@ function call_chargen(list) {
req.end(); req.end();
} else { } else {
console.log("End of list. closing servers"); console.log('End of list. closing servers');
proxy.close(); proxy.close();
chargen.close(); chargen.close();
done = true; done = true;
@ -95,11 +95,11 @@ function call_chargen(list) {
} }
serversRunning = 0; serversRunning = 0;
function ready () { function ready() {
if (++serversRunning < 2) return; if (++serversRunning < 2) return;
call_chargen([ 100, 1000, 10000, 100000, 1000000 ]); call_chargen([100, 1000, 10000, 100000, 1000000]);
} }
process.addListener('exit', function () { process.addListener('exit', function() {
assert.ok(done); assert.ok(done);
}); });

25
test/disabled/test-http-head-request.js

@ -1,15 +1,16 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var assert = require("assert"); var assert = require('assert');
var http = require("http"); var http = require('http');
var util = require("util"); var util = require('util');
var body = "hello world"; var body = 'hello world';
server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.writeHeader(200 , { 'Content-Length': body.length.toString() res.writeHeader(200,
, 'Content-Type': 'text/plain' {'Content-Length': body.length.toString(),
'Content-Type': 'text/plain'
}); });
console.log('method: ' + req.method); console.log('method: ' + req.method);
if (req.method != 'HEAD') res.write(body); if (req.method != 'HEAD') res.write(body);
@ -21,13 +22,13 @@ var gotEnd = false;
server.addListener('listening', function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var request = client.request("HEAD", "/"); var request = client.request('HEAD', '/');
request.addListener('response', function (response) { request.addListener('response', function(response) {
console.log('got response'); console.log('got response');
response.addListener("data", function () { response.addListener('data', function() {
process.exit(2); process.exit(2);
}); });
response.addListener("end", function () { response.addListener('end', function() {
process.exit(0); process.exit(0);
}); });
}); });

17
test/disabled/test-http-stress.js

@ -1,7 +1,7 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
http = require("http"); var http = require('http');
var request_count = 1000; var request_count = 1000;
var body = '{"ok": true}'; var body = '{"ok": true}';
@ -16,26 +16,27 @@ server.listen(common.PORT);
var requests_ok = 0; var requests_ok = 0;
var requests_complete = 0; var requests_complete = 0;
server.addListener('listening', function () { server.addListener('listening', function() {
for (var i = 0; i < request_count; i++) { for (var i = 0; i < request_count; i++) {
http.cat('http://localhost:'+common.PORT+'/', 'utf8', function (err, content) { http.cat('http://localhost:' + common.PORT + '/', 'utf8',
function(err, content) {
requests_complete++; requests_complete++;
if (err) { if (err) {
common.print("-"); common.print('-');
} else { } else {
assert.equal(body, content); assert.equal(body, content);
common.print("."); common.print('.');
requests_ok++; requests_ok++;
} }
if (requests_complete == request_count) { if (requests_complete == request_count) {
console.log("\nrequests ok: " + requests_ok); console.log('\nrequests ok: ' + requests_ok);
server.close(); server.close();
} }
}); });
} }
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(request_count, requests_complete); assert.equal(request_count, requests_complete);
assert.equal(request_count, requests_ok); assert.equal(request_count, requests_ok);
}); });

123
test/disabled/test-http-tls.js

@ -1,77 +1,84 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
net = require("net");
http = require("http"); var net = require('net');
url = require("url"); var http = require('http');
qs = require("querystring"); var url = require('url');
var qs = require('querystring');
var fs = require('fs'); var fs = require('fs');
var have_openssl; var have_openssl;
try { try {
var crypto = require('crypto'); var crypto = require('crypto');
var dummy_server = http.createServer(function(){}); var dummy_server = http.createServer(function() {});
dummy_server.setSecure(); dummy_server.setSecure();
have_openssl=true; have_openssl = true;
} catch (e) { } catch (e) {
have_openssl=false; have_openssl = false;
console.log("Not compiled with OPENSSL support."); console.log('Not compiled with OPENSSL support.');
process.exit(); process.exit();
} }
var request_number = 0; var request_number = 0;
var requests_sent = 0; var requests_sent = 0;
var server_response = ""; var server_response = '';
var client_got_eof = false; var client_got_eof = false;
var caPem = fs.readFileSync(common.fixturesDir+"/test_ca.pem", 'ascii'); var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii');
var certPem = fs.readFileSync(common.fixturesDir+"/test_cert.pem", 'ascii'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii');
var keyPem = fs.readFileSync(common.fixturesDir+"/test_key.pem", 'ascii'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii');
try{ try {
var credentials = crypto.createCredentials({key:keyPem, cert:certPem, ca:caPem}); var credentials = crypto.createCredentials(
{ key: keyPem,
cert: certPem,
ca: caPem
});
} catch (e) { } catch (e) {
console.log("Not compiled with OPENSSL support."); console.log('Not compiled with OPENSSL support.');
process.exit(); process.exit();
} }
var https_server = http.createServer(function (req, res) { var https_server = http.createServer(function(req, res) {
res.id = request_number; res.id = request_number;
req.id = request_number++; req.id = request_number++;
var verified = res.connection.verifyPeer(); var verified = res.connection.verifyPeer();
var peerDN = JSON.stringify(req.connection.getPeerCertificate()); var peerDN = JSON.stringify(req.connection.getPeerCertificate());
assert.equal(verified, true); assert.equal(verified, true);
assert.equal(peerDN, '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' assert.equal(peerDN,
+ '/O=node.js/OU=Test TLS Certificate/CN=localhost",' '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' +
+ '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' '/O=node.js/OU=Test TLS Certificate/CN=localhost",' +
+ '/OU=Test TLS Certificate/CN=localhost","valid_from":' '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' +
+ '"Nov 11 09:52:22 2009 GMT","valid_to":' '/OU=Test TLS Certificate/CN=localhost",' +
+ '"Nov 6 09:52:22 2029 GMT",' '"valid_from":"Nov 11 09:52:22 2009 GMT",' +
+ '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF"}'); '"valid_to":"Nov 6 09:52:22 2029 GMT",' +
'"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' +
'5A:71:38:52:EC:8A:DF"}');
if (req.id == 0) { if (req.id == 0) {
assert.equal("GET", req.method); assert.equal('GET', req.method);
assert.equal("/hello", url.parse(req.url).pathname); assert.equal('/hello', url.parse(req.url).pathname);
assert.equal("world", qs.parse(url.parse(req.url).query).hello); assert.equal('world', qs.parse(url.parse(req.url).query).hello);
assert.equal("b==ar", qs.parse(url.parse(req.url).query).foo); assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo);
} }
if (req.id == 1) { if (req.id == 1) {
assert.equal("POST", req.method); assert.equal('POST', req.method);
assert.equal("/quit", url.parse(req.url).pathname); assert.equal('/quit', url.parse(req.url).pathname);
} }
if (req.id == 2) { if (req.id == 2) {
assert.equal("foo", req.headers['x-x']); assert.equal('foo', req.headers['x-x']);
} }
if (req.id == 3) { if (req.id == 3) {
assert.equal("bar", req.headers['x-x']); assert.equal('bar', req.headers['x-x']);
this.close(); this.close();
//console.log("server closed"); //console.log('server closed');
} }
setTimeout(function () { setTimeout(function() {
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(url.parse(req.url).pathname); res.write(url.parse(req.url).pathname);
res.end(); res.end();
}, 1); }, 1);
@ -80,65 +87,67 @@ var https_server = http.createServer(function (req, res) {
https_server.setSecure(credentials); https_server.setSecure(credentials);
https_server.listen(common.PORT); https_server.listen(common.PORT);
https_server.addListener("listening", function() { https_server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.setEncoding("utf8"); c.setEncoding('utf8');
c.addListener("connect", function () { c.addListener('connect', function() {
c.setSecure(credentials); c.setSecure(credentials);
}); });
c.addListener("secure", function () { c.addListener('secure', function() {
var verified = c.verifyPeer(); var verified = c.verifyPeer();
var peerDN = JSON.stringify(c.getPeerCertificate()); var peerDN = JSON.stringify(c.getPeerCertificate());
assert.equal(verified, true); assert.equal(verified, true);
assert.equal(peerDN, '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' assert.equal(peerDN,
+ '/O=node.js/OU=Test TLS Certificate/CN=localhost",' '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' +
+ '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' '/O=node.js/OU=Test TLS Certificate/CN=localhost",' +
+ '/OU=Test TLS Certificate/CN=localhost","valid_from":' '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' +
+ '"Nov 11 09:52:22 2009 GMT","valid_to":' '/OU=Test TLS Certificate/CN=localhost",' +
+ '"Nov 6 09:52:22 2029 GMT",' '"valid_from":"Nov 11 09:52:22 2009 GMT",' +
+ '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF"}'); '"valid_to":"Nov 6 09:52:22 2029 GMT",' +
c.write( "GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n" ); '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' +
'5A:71:38:52:EC:8A:DF"}');
c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n');
requests_sent += 1; requests_sent += 1;
}); });
c.addListener("data", function (chunk) { c.addListener('data', function(chunk) {
server_response += chunk; server_response += chunk;
if (requests_sent == 1) { if (requests_sent == 1) {
c.write("POST /quit HTTP/1.1\r\n\r\n"); c.write('POST /quit HTTP/1.1\r\n\r\n');
requests_sent += 1; requests_sent += 1;
} }
if (requests_sent == 2) { if (requests_sent == 2) {
c.write("GET / HTTP/1.1\r\nX-X: foo\r\n\r\n" 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"); 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n');
c.end(); c.end();
assert.equal(c.readyState, "readOnly"); assert.equal(c.readyState, 'readOnly');
requests_sent += 2; requests_sent += 2;
} }
}); });
c.addListener("end", function () { c.addListener('end', function() {
client_got_eof = true; client_got_eof = true;
}); });
c.addListener("close", function () { c.addListener('close', function() {
assert.equal(c.readyState, "closed"); assert.equal(c.readyState, 'closed');
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(4, request_number); assert.equal(4, request_number);
assert.equal(4, requests_sent); assert.equal(4, requests_sent);
var hello = new RegExp("/hello"); var hello = new RegExp('/hello');
assert.equal(true, hello.exec(server_response) != null); assert.equal(true, hello.exec(server_response) != null);
var quit = new RegExp("/quit"); var quit = new RegExp('/quit');
assert.equal(true, quit.exec(server_response) != null); assert.equal(true, quit.exec(server_response) != null);
assert.equal(true, client_got_eof); assert.equal(true, client_got_eof);

6
test/disabled/test-idle-watcher.js

@ -1,15 +1,15 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var complete = false; var complete = false;
var idle = new process.IdleWatcher(); var idle = new process.IdleWatcher();
idle.callback = function () { idle.callback = function() {
complete = true; complete = true;
idle.stop(); idle.stop();
}; };
idle.setPriority(process.EVMAXPRI); idle.setPriority(process.EVMAXPRI);
idle.start(); idle.start();
process.addListener('exit', function () { process.addListener('exit', function() {
assert.ok(complete); assert.ok(complete);
}); });

31
test/disabled/test-net-fd-passing.js

@ -1,34 +1,37 @@
process.mixin(require("../common")); var common = require('../common');
net = require("net"); var assert = require('assert');
var net = require('net');
var tests_run = 0; var tests_run = 0;
function fdPassingTest(path, port) { function fdPassingTest(path, port) {
var greeting = "howdy"; var greeting = 'howdy';
var message = "beep toot"; var message = 'beep toot';
var expectedData = ["[greeting] " + greeting, "[echo] " + message]; var expectedData = ['[greeting] ' + greeting, '[echo] ' + message];
var receiverArgs = [common.fixturesDir + "/net-fd-passing-receiver.js", path, greeting]; var receiverArgs = [common.fixturesDir + '/net-fd-passing-receiver.js',
path,
greeting];
var receiver = process.createChildProcess(process.ARGV[0], receiverArgs); var receiver = process.createChildProcess(process.ARGV[0], receiverArgs);
var initializeSender = function() { var initializeSender = function() {
var fdHighway = new net.Socket(); var fdHighway = new net.Socket();
fdHighway.addListener("connect", function() { fdHighway.addListener('connect', function() {
var sender = net.createServer(function(socket) { var sender = net.createServer(function(socket) {
fdHighway.sendFD(socket); fdHighway.sendFD(socket);
socket.flush(); socket.flush();
socket.forceClose(); // want to close() the fd, not shutdown() socket.forceClose(); // want to close() the fd, not shutdown()
}); });
sender.addListener("listening", function() { sender.addListener('listening', function() {
var client = net.createConnection(port); var client = net.createConnection(port);
client.addListener("connect", function() { client.addListener('connect', function() {
client.write(message); client.write(message);
}); });
client.addListener("data", function(data) { client.addListener('data', function(data) {
assert.equal(expectedData[0], data); assert.equal(expectedData[0], data);
if (expectedData.length > 1) { if (expectedData.length > 1) {
expectedData.shift(); expectedData.shift();
@ -51,17 +54,17 @@ function fdPassingTest(path, port) {
}; };
receiver.addListener("output", function(data) { receiver.addListener('output', function(data) {
var initialized = false; var initialized = false;
if ((! initialized) && (data == "ready")) { if ((! initialized) && (data == 'ready')) {
initializeSender(); initializeSender();
initialized = true; initialized = true;
} }
}); });
} }
fdPassingTest("/tmp/passing-socket-test", 31075); fdPassingTest('/tmp/passing-socket-test', 31075);
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(1, tests_run); assert.equal(1, tests_run);
}); });

91
test/disabled/test-net-tls-pummel.js

@ -1,49 +1,51 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
net = require("net");
fs=require("fs"); var net = require('net');
var fs = require('fs');
var tests_run = 0; var tests_run = 0;
function tlsTest (port, host, caPem, keyPem, certPem) { function tlsTest(port, host, caPem, keyPem, certPem) {
var N = 50; var N = 50;
var count = 0; var count = 0;
var sent_final_ping = false; var sent_final_ping = false;
var server = net.createServer(function (socket) { var server = net.createServer(function(socket) {
assert.equal(true, socket.remoteAddress !== null); assert.equal(true, socket.remoteAddress !== null);
assert.equal(true, socket.remoteAddress !== undefined); assert.equal(true, socket.remoteAddress !== undefined);
if (host === "127.0.0.1") if (host === '127.0.0.1')
assert.equal(socket.remoteAddress, "127.0.0.1"); assert.equal(socket.remoteAddress, '127.0.0.1');
else if (host == null) else if (host == null)
assert.equal(socket.remoteAddress, "127.0.0.1"); assert.equal(socket.remoteAddress, '127.0.0.1');
socket.setEncoding("utf8"); socket.setEncoding('utf8');
socket.setNoDelay(); socket.setNoDelay();
socket.timeout = 0; socket.timeout = 0;
socket.addListener("data", function (data) { socket.addListener('data', function(data) {
var verified = socket.verifyPeer(); var verified = socket.verifyPeer();
var peerDN = socket.getPeerCertificate("DNstring"); var peerDN = socket.getPeerCertificate('DNstring');
assert.equal(verified, 1); assert.equal(verified, 1);
assert.equal(peerDN, "C=UK,ST=Acknack Ltd,L=Rhys Jones,O=node.js," assert.equal(peerDN,
+ "OU=Test TLS Certificate,CN=localhost"); 'C=UK,ST=Acknack Ltd,L=Rhys Jones,O=node.js,' +
console.log("server got: " + JSON.stringify(data)); 'OU=Test TLS Certificate,CN=localhost');
assert.equal("open", socket.readyState); console.log('server got: ' + JSON.stringify(data));
assert.equal('open', socket.readyState);
assert.equal(true, count <= N); assert.equal(true, count <= N);
if (/PING/.exec(data)) { if (/PING/.exec(data)) {
socket.write("PONG"); socket.write('PONG');
} }
}); });
socket.addListener("end", function () { socket.addListener('end', function() {
assert.equal("writeOnly", socket.readyState); assert.equal('writeOnly', socket.readyState);
socket.end(); socket.end();
}); });
socket.addListener("close", function (had_error) { socket.addListener('close', function(had_error) {
assert.equal(false, had_error); assert.equal(false, had_error);
assert.equal("closed", socket.readyState); assert.equal('closed', socket.readyState);
socket.server.close(); socket.server.close();
}); });
}); });
@ -53,43 +55,44 @@ function tlsTest (port, host, caPem, keyPem, certPem) {
var client = net.createConnection(port, host); var client = net.createConnection(port, host);
client.setEncoding("utf8"); client.setEncoding('utf8');
client.setSecure('X509_PEM', caPem, 0, keyPem, caPem); client.setSecure('X509_PEM', caPem, 0, keyPem, caPem);
client.addListener("connect", function () { client.addListener('connect', function() {
assert.equal("open", client.readyState); assert.equal('open', client.readyState);
var verified = client.verifyPeer(); var verified = client.verifyPeer();
var peerDN = client.getPeerCertificate("DNstring"); var peerDN = client.getPeerCertificate('DNstring');
assert.equal(verified, 1); assert.equal(verified, 1);
assert.equal(peerDN, "C=UK,ST=Acknack Ltd,L=Rhys Jones,O=node.js," assert.equal(peerDN,
+ "OU=Test TLS Certificate,CN=localhost"); 'C=UK,ST=Acknack Ltd,L=Rhys Jones,O=node.js,' +
client.write("PING"); 'OU=Test TLS Certificate,CN=localhost');
client.write('PING');
}); });
client.addListener("data", function (data) { client.addListener('data', function(data) {
assert.equal("PONG", data); assert.equal('PONG', data);
count += 1; count += 1;
console.log("client got PONG"); console.log('client got PONG');
if (sent_final_ping) { if (sent_final_ping) {
assert.equal("readOnly", client.readyState); assert.equal('readOnly', client.readyState);
return; return;
} else { } else {
assert.equal("open", client.readyState); assert.equal('open', client.readyState);
} }
if (count < N) { if (count < N) {
client.write("PING"); client.write('PING');
} else { } else {
sent_final_ping = true; sent_final_ping = true;
client.write("PING"); client.write('PING');
client.end(); client.end();
} }
}); });
client.addListener("close", function () { client.addListener('close', function() {
assert.equal(N+1, count); assert.equal(N + 1, count);
assert.equal(true, sent_final_ping); assert.equal(true, sent_final_ping);
tests_run += 1; tests_run += 1;
}); });
@ -100,24 +103,24 @@ var have_tls;
try { try {
var dummy_server = net.createServer(); var dummy_server = net.createServer();
dummy_server.setSecure(); dummy_server.setSecure();
have_tls=true; have_tls = true;
} catch (e) { } catch (e) {
have_tls=false; have_tls = false;
} }
if (have_tls) { if (have_tls) {
var caPem = fs.readFileSync(common.fixturesDir+"/test_ca.pem"); var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem');
var certPem = fs.readFileSync(common.fixturesDir+"/test_cert.pem"); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem');
var keyPem = fs.readFileSync(common.fixturesDir+"/test_key.pem"); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem');
/* All are run at once, so run on different ports */ /* All are run at once, so run on different ports */
tlsTest(common.PORT, "localhost", caPem, keyPem, certPem); tlsTest(common.PORT, 'localhost', caPem, keyPem, certPem);
tlsTest(common.PORT+1, null, caPem, keyPem, certPem); tlsTest(common.PORT + 1, null, caPem, keyPem, certPem);
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(2, tests_run); assert.equal(2, tests_run);
}); });
} else { } else {
console.log("Not compiled with TLS support -- skipping test"); console.log('Not compiled with TLS support -- skipping test');
process.exit(0); process.exit(0);
} }

84
test/disabled/test-net-tls.js

@ -6,56 +6,62 @@ var net = require('net');
var have_openssl; var have_openssl;
try { try {
var crypto = require('crypto'); var crypto = require('crypto');
have_openssl=true; have_openssl = true;
} catch (e) { } catch (e) {
have_openssl=false; have_openssl = false;
console.log("Not compiled with OPENSSL support."); console.log('Not compiled with OPENSSL support.');
process.exit(); process.exit();
} }
var caPem = fs.readFileSync(common.fixturesDir+"/test_ca.pem", 'ascii'); var caPem = fs.readFileSync(common.fixturesDir + '/test_ca.pem', 'ascii');
var certPem = fs.readFileSync(common.fixturesDir+"/test_cert.pem", 'ascii'); var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii');
var keyPem = fs.readFileSync(common.fixturesDir+"/test_key.pem", 'ascii'); var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii');
try{ try {
var credentials = crypto.createCredentials({key:keyPem, cert:certPem, ca:caPem}); var credentials = crypto.createCredentials(
{ key: keyPem,
cert: certPem,
ca: caPem
});
} catch (e) { } catch (e) {
console.log("Not compiled with OPENSSL support."); console.log('Not compiled with OPENSSL support.');
process.exit(); process.exit();
} }
var testData = "TEST123"; var testData = 'TEST123';
var serverData = ''; var serverData = '';
var clientData = ''; var clientData = '';
var gotSecureServer = false; var gotSecureServer = false;
var gotSecureClient = false; var gotSecureClient = false;
var secureServer = net.createServer(function (connection) { var secureServer = net.createServer(function(connection) {
var self = this; var self = this;
connection.setSecure(credentials); connection.setSecure(credentials);
connection.setEncoding("UTF8"); connection.setEncoding('UTF8');
connection.addListener("secure", function () { connection.addListener('secure', function() {
gotSecureServer = true; gotSecureServer = true;
var verified = connection.verifyPeer(); var verified = connection.verifyPeer();
var peerDN = JSON.stringify(connection.getPeerCertificate()); var peerDN = JSON.stringify(connection.getPeerCertificate());
assert.equal(verified, true); assert.equal(verified, true);
assert.equal(peerDN, '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' assert.equal(peerDN,
+ '/O=node.js/OU=Test TLS Certificate/CN=localhost",' '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' +
+ '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' '/O=node.js/OU=Test TLS Certificate/CN=localhost",' +
+ '/OU=Test TLS Certificate/CN=localhost","valid_from":' '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' +
+ '"Nov 11 09:52:22 2009 GMT","valid_to":' '/OU=Test TLS Certificate/CN=localhost",' +
+ '"Nov 6 09:52:22 2029 GMT",' '"valid_from":"Nov 11 09:52:22 2009 GMT",' +
+ '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF"}'); '"valid_to":"Nov 6 09:52:22 2029 GMT",' +
'"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' +
'5A:71:38:52:EC:8A:DF"}');
}); });
connection.addListener("data", function (chunk) { connection.addListener('data', function(chunk) {
serverData += chunk; serverData += chunk;
connection.write(chunk); connection.write(chunk);
}); });
connection.addListener("end", function () { connection.addListener('end', function() {
assert.equal(serverData, testData); assert.equal(serverData, testData);
connection.end(); connection.end();
self.close(); self.close();
@ -63,41 +69,43 @@ var secureServer = net.createServer(function (connection) {
}); });
secureServer.listen(common.PORT); secureServer.listen(common.PORT);
secureServer.addListener("listening", function() { secureServer.addListener('listening', function() {
var secureClient = net.createConnection(common.PORT); var secureClient = net.createConnection(common.PORT);
secureClient.setEncoding("UTF8"); secureClient.setEncoding('UTF8');
secureClient.addListener("connect", function () { secureClient.addListener('connect', function() {
secureClient.setSecure(credentials); secureClient.setSecure(credentials);
}); });
secureClient.addListener("secure", function () { secureClient.addListener('secure', function() {
gotSecureClient = true; gotSecureClient = true;
var verified = secureClient.verifyPeer(); var verified = secureClient.verifyPeer();
var peerDN = JSON.stringify(secureClient.getPeerCertificate()); var peerDN = JSON.stringify(secureClient.getPeerCertificate());
assert.equal(verified, true); assert.equal(verified, true);
assert.equal(peerDN, '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' assert.equal(peerDN,
+ '/O=node.js/OU=Test TLS Certificate/CN=localhost",' '{"subject":"/C=UK/ST=Acknack Ltd/L=Rhys Jones' +
+ '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' '/O=node.js/OU=Test TLS Certificate/CN=localhost",' +
+ '/OU=Test TLS Certificate/CN=localhost","valid_from":' '"issuer":"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js' +
+ '"Nov 11 09:52:22 2009 GMT","valid_to":' '/OU=Test TLS Certificate/CN=localhost",' +
+ '"Nov 6 09:52:22 2029 GMT",' '"valid_from":"Nov 11 09:52:22 2009 GMT",' +
+ '"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF"}'); '"valid_to":"Nov 6 09:52:22 2029 GMT",' +
'"fingerprint":"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:' +
'5A:71:38:52:EC:8A:DF"}');
secureClient.write(testData); secureClient.write(testData);
secureClient.end(); secureClient.end();
}); });
secureClient.addListener("data", function (chunk) { secureClient.addListener('data', function(chunk) {
clientData += chunk; clientData += chunk;
}); });
secureClient.addListener("end", function () { secureClient.addListener('end', function() {
assert.equal(clientData, testData); assert.equal(clientData, testData);
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.ok(gotSecureServer, "Did not get secure event for server"); assert.ok(gotSecureServer, 'Did not get secure event for server');
assert.ok(gotSecureClient, "Did not get secure event for clientr"); assert.ok(gotSecureClient, 'Did not get secure event for client');
}); });

14
test/disabled/test-process-title.js

@ -1,5 +1,5 @@
var common = require("../common"); var common = require('../common');
var assert = common.assert; var assert = require('assert');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
if (process.title === '') { if (process.title === '') {
@ -16,11 +16,11 @@ function verifyProcessName(str, callback) {
var buf = ''; var buf = '';
ps = spawn('ps'); ps = spawn('ps');
ps.stdout.setEncoding('utf8'); ps.stdout.setEncoding('utf8');
ps.stdout.addListener("data", function (s) { buf += s; }); ps.stdout.addListener('data', function(s) { buf += s; });
ps.addListener("exit", function (c) { ps.addListener('exit', function(c) {
try { try {
assert.equal(0, c); assert.equal(0, c);
assert.ok(new RegExp(process.pid+' ', 'm').test(buf)); assert.ok(new RegExp(process.pid + ' ', 'm').test(buf));
assert.ok(new RegExp(str, 'm').test(buf)); assert.ok(new RegExp(str, 'm').test(buf));
callback(); callback();
} catch (err) { } catch (err) {
@ -29,10 +29,10 @@ function verifyProcessName(str, callback) {
}); });
} }
verifyProcessName("3kd023mslkfp--unique-string--sksdf", function(err){ verifyProcessName('3kd023mslkfp--unique-string--sksdf', function(err) {
if (err) throw err; if (err) throw err;
console.log('title is now %j', process.title); console.log('title is now %j', process.title);
verifyProcessName("3kd023mslxxx--unique-string--xxx", function(err){ verifyProcessName('3kd023mslxxx--unique-string--xxx', function(err) {
if (err) throw err; if (err) throw err;
console.log('title is now %j', process.title); console.log('title is now %j', process.title);
}); });

14
test/disabled/test-readline.js

@ -1,8 +1,8 @@
// Can't test this when 'make test' doesn't assign a tty to the stdout. // Can't test this when 'make test' doesn't assign a tty to the stdout.
// Yet another use-case for require('tty').spawn ? // Yet another use-case for require('tty').spawn ?
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var readline = require("readline"); var readline = require('readline');
var key = { var key = {
xterm: { xterm: {
@ -28,12 +28,14 @@ var key = {
var readlineFakeStream = function() { var readlineFakeStream = function() {
var written_bytes = []; var written_bytes = [];
var rl = readline.createInterface({ var rl = readline.createInterface(
fd: 1, { fd: 1,
write: function(b) { write: function(b) {
written_bytes.push(b); written_bytes.push(b);
}}, function (text) { }
return [[], ""]; },
function(text) {
return [[], ''];
}); });
rl.written_bytes = written_bytes; rl.written_bytes = written_bytes;
return rl; return rl;

18
test/disabled/test-remote-module-loading.js

@ -1,32 +1,32 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var http = require('http'); var http = require('http');
var util = require('util'); var util = require('util');
var url = require("url"); var url = require('url');
var modulesLoaded = 0; var modulesLoaded = 0;
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
var body = 'exports.httpPath = function() {'+ var body = 'exports.httpPath = function() {' +
'return '+JSON.stringify(url.parse(req.url).pathname)+';'+ 'return ' + JSON.stringify(url.parse(req.url).pathname) + ';' +
'};'; '};';
res.writeHead(200, {'Content-Type': 'text/javascript'}); res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(body); res.write(body);
res.end(); res.end();
}); });
server.listen(common.PORT); server.listen(common.PORT);
assert.throws(function () { assert.throws(function() {
var httpModule = require('http://localhost:'+common.PORT+'/moduleA.js'); var httpModule = require('http://localhost:' + common.PORT + '/moduleA.js');
assert.equal('/moduleA.js', httpModule.httpPath()); assert.equal('/moduleA.js', httpModule.httpPath());
modulesLoaded++; modulesLoaded++;
}); });
var nodeBinary = process.ARGV[0]; var nodeBinary = process.ARGV[0];
var cmd = 'NODE_PATH='+libDir+' '+nodeBinary+' http://localhost:'+common.PORT+'/moduleB.js'; var cmd = 'NODE_PATH=' + common.libDir + ' ' + nodeBinary +
' http://localhost:' + common.PORT + '/moduleB.js';
util.exec(cmd, function (err, stdout, stderr) { util.exec(cmd, function(err, stdout, stderr) {
if (err) throw err; if (err) throw err;
console.log('success!'); console.log('success!');
modulesLoaded++; modulesLoaded++;

4
test/disabled/test-setuidgid.js

@ -1,6 +1,5 @@
// Requires special privlages // Requires special privlages
var common = require('../common'); var common = require('../common');
var assert = require('assert');;
var assert = require('assert'); var assert = require('assert');
var oldgid = process.getgid(); var oldgid = process.getgid();
@ -16,8 +15,7 @@ assert.notEqual(newuid, olduid, 'uids expected to be different');
try { try {
process.setuid('nobody1234'); process.setuid('nobody1234');
} catch (e) { } catch (e) {
assert.equal( assert.equal(e.message,
e.message,
'failed to resolve group', 'failed to resolve group',
'unexpected error message' 'unexpected error message'
); );

28
test/disabled/test-tls-server.js

@ -1,29 +1,31 @@
// Example of new TLS API. Test with: // Example of new TLS API. Test with:
// //
// openssl s_client -connect localhost:12346 -key test/fixtures/agent.key -cert test/fixtures/agent.crt // $> openssl s_client -connect localhost:12346 \
// openssl s_client -connect localhost:12346 // -key test/fixtures/agent.key -cert test/fixtures/agent.crt
//
// $> openssl s_client -connect localhost:12346
// //
var common = require('../common'); var common = require('../common');
var tls = require('tls'); var tls = require('tls');
var fs = require('fs'); var fs = require('fs');
var join = require('path').join; var join = require('path').join;
var key = fs.readFileSync(join(common.fixturesDir, "agent.key")).toString(); var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString();
var cert = fs.readFileSync(join(common.fixturesDir, "agent.crt")).toString(); var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString();
s = tls.Server({ key: key, cert: cert, unauthorizedPeers: false }); s = tls.Server({key: key, cert: cert, unauthorizedPeers: false});
s.listen(common.PORT, function () { s.listen(common.PORT, function() {
console.log("TLS server on 127.0.0.1:%d", common.PORT); console.log('TLS server on 127.0.0.1:%d', common.PORT);
}); });
s.on('authorized', function (c) { s.on('authorized', function(c) {
console.log("authed connection"); console.log('authed connection');
c.end("bye authorized friend.\n"); c.end('bye authorized friend.\n');
}); });
s.on('unauthorized', function (c, e) { s.on('unauthorized', function(c, e) {
console.log("unauthed connection: %s", e); console.log('unauthed connection: %s', e);
c.end("bye unauthorized person.\n"); c.end('bye unauthorized person.\n');
}); });

47
test/disabled/tls_client.js

@ -1,42 +1,43 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var util=require('util');
var net=require('net');
var fs=require('fs');
var crypto=require('crypto');
//var client = net.createConnection(4443, "localhost"); var util = require('util');
var client = net.createConnection(443, "www.microsoft.com"); var net = require('net');
//var client = net.createConnection(443, "www.google.com"); var fs = require('fs');
var crypto = require('crypto');
var caPem = fs.readFileSync(common.fixturesDir+"/msca.pem"); //var client = net.createConnection(4443, 'localhost');
//var caPem = fs.readFileSync("ca.pem"); var client = net.createConnection(443, 'www.microsoft.com');
//var client = net.createConnection(443, 'www.google.com');
try{ var caPem = fs.readFileSync(common.fixturesDir + '/msca.pem');
var credentials = crypto.createCredentials({ca:caPem}); //var caPem = fs.readFileSync('ca.pem');
try {
var credentials = crypto.createCredentials({ca: caPem});
} catch (e) { } catch (e) {
console.log("Not compiled with OPENSSL support."); console.log('Not compiled with OPENSSL support.');
process.exit(); process.exit();
} }
client.setEncoding("UTF8"); client.setEncoding('UTF8');
client.addListener("connect", function () { client.addListener('connect', function() {
console.log("client connected."); console.log('client connected.');
client.setSecure(credentials); client.setSecure(credentials);
}); });
client.addListener("secure", function () { client.addListener('secure', function() {
console.log("client secure : "+JSON.stringify(client.getCipher())); console.log('client secure : ' + JSON.stringify(client.getCipher()));
console.log(JSON.stringify(client.getPeerCertificate())); console.log(JSON.stringify(client.getPeerCertificate()));
console.log("verifyPeer : "+client.verifyPeer()); console.log('verifyPeer : ' + client.verifyPeer());
client.write("GET / HTTP/1.0\r\n\r\n"); client.write('GET / HTTP/1.0\r\n\r\n');
}); });
client.addListener("data", function (chunk) { client.addListener('data', function(chunk) {
common.error(chunk); common.error(chunk);
}); });
client.addListener("end", function () { client.addListener('end', function() {
console.log("client disconnected."); console.log('client disconnected.');
}); });

43
test/disabled/tls_server.js

@ -1,37 +1,42 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var util=require('util'); var util = require('util');
var net=require('net'); var net = require('net');
var fs=require('fs'); var fs = require('fs');
var crypto=require('crypto'); var crypto = require('crypto');
var keyPem = fs.readFileSync(common.fixturesDir + "/cert.pem"); var keyPem = fs.readFileSync(common.fixturesDir + '/cert.pem');
var certPem = fs.readFileSync(common.fixturesDir + "/cert.pem"); var certPem = fs.readFileSync(common.fixturesDir + '/cert.pem');
try{ try {
var credentials = crypto.createCredentials({key:keyPem, cert:certPem}); var credentials = crypto.createCredentials({key: keyPem, cert: certPem});
} catch (e) { } catch (e) {
console.log("Not compiled with OPENSSL support."); console.log('Not compiled with OPENSSL support.');
process.exit(); process.exit();
} }
var i = 0; var i = 0;
var server = net.createServer(function (connection) { var server = net.createServer(function(connection) {
connection.setSecure(credentials); connection.setSecure(credentials);
connection.setEncoding("binary"); connection.setEncoding('binary');
connection.addListener("secure", function () { connection.addListener('secure', function() {
//console.log("Secure"); //console.log('Secure');
}); });
connection.addListener("data", function (chunk) { connection.addListener('data', function(chunk) {
console.log("recved: " + JSON.stringify(chunk)); console.log('recved: ' + JSON.stringify(chunk));
connection.write("HTTP/1.0 200 OK\r\nContent-type: text/plain\r\nContent-length: 9\r\n\r\nOK : "+i+"\r\n\r\n"); connection.write('HTTP/1.0 200 OK\r\n' +
i=i+1; 'Content-type: text/plain\r\n' +
'Content-length: 9\r\n' +
'\r\n' +
'OK : ' + i +
'\r\n\r\n');
i = i + 1;
connection.end(); connection.end();
}); });
connection.addListener("end", function () { connection.addListener('end', function() {
connection.end(); connection.end();
}); });

2
test/fixtures/echo.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
common.print('hello world\r\n'); common.print('hello world\r\n');

2
test/fixtures/print-chars-from-buffer.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var n = parseInt(process.argv[2]); var n = parseInt(process.argv[2]);

4
test/message/undefined_reference_in_new_context.js

@ -1,5 +1,5 @@
common = require('../common'); var common = require('../common');
assert = common.assert; var assert = require('assert');
common.error('before'); common.error('before');

2
test/pummel/test-child-process-spawn-loop.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;

2
test/pummel/test-http-client-reconnect-bug.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var net = require('net'), var net = require('net'),
util = require('util'), util = require('util'),

2
test/pummel/test-keep-alive.js

@ -1,6 +1,6 @@
// This test requires the program 'ab' // This test requires the program 'ab'
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var http = require('http'); var http = require('http');
var exec = require('child_process').exec; var exec = require('child_process').exec;

2
test/pummel/test-net-many-clients.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var net = require('net'); var net = require('net');
// settings // settings

2
test/pummel/test-net-pause.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = common.assert; var assert = require('assert');
var net = require('net'); var net = require('net');
var N = 200; var N = 200;

2
test/pummel/test-net-pingpong-delay.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var net = require('net'); var net = require('net');

2
test/pummel/test-net-pingpong.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var net = require('net'); var net = require('net');
var tests_run = 0; var tests_run = 0;

2
test/pummel/test-net-throttle.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var net = require('net'); var net = require('net');
var N = 160 * 1024; // 30kb var N = 160 * 1024; // 30kb

7
test/pummel/test-net-timeout.js

@ -1,5 +1,5 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var net = require('net'); var net = require('net');
var exchanges = 0; var exchanges = 0;
@ -18,8 +18,9 @@ var echo_server = net.createServer(function(socket) {
}); });
socket.addListener('error', function(e) { socket.addListener('error', function(e) {
throw new Error('Server side socket should not get error. We disconnect willingly.'); throw new Error('Server side socket should not get error. ' +
}) 'We disconnect willingly.');
});
socket.addListener('data', function(d) { socket.addListener('data', function(d) {
console.log(d); console.log(d);

14
test/pummel/test-timers.js

@ -46,33 +46,33 @@ setInterval(function() {
// Single param: // Single param:
setTimeout(function(param){ setTimeout(function(param) {
assert.equal('test param', param); assert.equal('test param', param);
}, 1000, 'test param'); }, 1000, 'test param');
var interval_count2 = 0; var interval_count2 = 0;
setInterval(function(param){ setInterval(function(param) {
++interval_count2; ++interval_count2;
assert.equal('test param', param); assert.equal('test param', param);
if(interval_count2 == 3) if (interval_count2 == 3)
clearInterval(this); clearInterval(this);
}, 1000, 'test param'); }, 1000, 'test param');
// Multiple param // Multiple param
setTimeout(function(param1, param2){ setTimeout(function(param1, param2) {
assert.equal('param1', param1); assert.equal('param1', param1);
assert.equal('param2', param2); assert.equal('param2', param2);
}, 1000, 'param1', 'param2'); }, 1000, 'param1', 'param2');
var interval_count3 = 0; var interval_count3 = 0;
setInterval(function(param1, param2){ setInterval(function(param1, param2) {
++interval_count3; ++interval_count3;
assert.equal('param1', param1); assert.equal('param1', param1);
assert.equal('param2', param2); assert.equal('param2', param2);
if(interval_count3 == 3) if (interval_count3 == 3)
clearInterval(this); clearInterval(this);
}, 1000, 'param1', 'param2'); }, 1000, 'param1', 'param2');
@ -86,7 +86,7 @@ var interval4 = setInterval(function() {
// we should be able to clearTimeout multiple times without breakage. // we should be able to clearTimeout multiple times without breakage.
var expectedTimeouts = 3; var expectedTimeouts = 3;
function t () { function t() {
expectedTimeouts--; expectedTimeouts--;
} }

2
test/pummel/test-watch-file.js

@ -10,7 +10,7 @@ var f2 = path.join(common.fixturesDir, 'x2.txt');
console.log('watching for changes of ' + f); console.log('watching for changes of ' + f);
var changes = 0; var changes = 0;
function watchFile () { function watchFile() {
fs.watchFile(f, function(curr, prev) { fs.watchFile(f, function(curr, prev) {
console.log(f + ' change'); console.log(f + ' change');
changes++; changes++;

30
test/simple/test-http-1.0.js

@ -1,44 +1,44 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var net = require("net"); var net = require('net');
var http = require("http"); var http = require('http');
var body = "hello world\n"; var body = 'hello world\n';
var server_response = ""; var server_response = '';
var client_got_eof = false; var client_got_eof = false;
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
assert.equal('1.0', req.httpVersion); assert.equal('1.0', req.httpVersion);
assert.equal(1, req.httpVersionMajor); assert.equal(1, req.httpVersionMajor);
assert.equal(0, req.httpVersionMinor); assert.equal(0, req.httpVersionMinor);
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(body); res.end(body);
}) });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.setEncoding("utf8"); c.setEncoding('utf8');
c.addListener("connect", function () { c.addListener('connect', function() {
c.write( "GET / HTTP/1.0\r\n\r\n" ); c.write('GET / HTTP/1.0\r\n\r\n');
}); });
c.addListener("data", function (chunk) { c.addListener('data', function(chunk) {
console.log(chunk); console.log(chunk);
server_response += chunk; server_response += chunk;
}); });
c.addListener("end", function () { c.addListener('end', function() {
client_got_eof = true; client_got_eof = true;
c.end(); c.end();
server.close(); server.close();
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
var m = server_response.split("\r\n\r\n"); var m = server_response.split('\r\n\r\n');
assert.equal(m[1], body); assert.equal(m[1], body);
assert.equal(true, client_got_eof); assert.equal(true, client_got_eof);
}); });

9
test/simple/test-http-304.js

@ -4,13 +4,14 @@ var assert = require('assert');
var http = require('http'); var http = require('http');
var childProcess = require('child_process'); var childProcess = require('child_process');
var s = http.createServer(function (request, response) { var s = http.createServer(function(request, response) {
response.writeHead(304); response.writeHead(304);
response.end(); response.end();
}); });
s.listen(common.PORT, function () { s.listen(common.PORT, function() {
childProcess.exec('curl -i http://127.0.0.1:'+common.PORT+'/', function (err, stdout, stderr) { childProcess.exec('curl -i http://127.0.0.1:' + common.PORT + '/',
function(err, stdout, stderr) {
if (err) throw err; if (err) throw err;
s.close(); s.close();
common.error('curled response correctly'); common.error('curled response correctly');
@ -18,4 +19,4 @@ s.listen(common.PORT, function () {
}); });
}); });
console.log('Server running at http://127.0.0.1:'+common.PORT+'/') console.log('Server running at http://127.0.0.1:' + common.PORT + '/');

10
test/simple/test-http-allow-req-after-204-res.js

@ -3,12 +3,12 @@ var http = require('http');
var assert = require('assert'); var assert = require('assert');
// first 204 or 304 works, subsequent anything fails // first 204 or 304 works, subsequent anything fails
var codes = [ 204, 200 ]; var codes = [204, 200];
// Methods don't really matter, but we put in something realistic. // Methods don't really matter, but we put in something realistic.
var methods = ['DELETE', 'DELETE']; var methods = ['DELETE', 'DELETE'];
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
var code = codes.shift(); var code = codes.shift();
assert.equal('number', typeof code); assert.equal('number', typeof code);
assert.ok(code > 0); assert.ok(code > 0);
@ -21,13 +21,13 @@ var client = http.createClient(common.PORT);
function nextRequest() { function nextRequest() {
var method = methods.shift(); var method = methods.shift();
console.error("writing request: %s", method); console.error('writing request: %s', method);
var request = client.request(method, '/'); var request = client.request(method, '/');
request.on('response', function (response) { request.on('response', function(response) {
response.on('end', function() { response.on('end', function() {
if (methods.length == 0) { if (methods.length == 0) {
console.error("close server"); console.error('close server');
server.close(); server.close();
} else { } else {
// throws error: // throws error:

28
test/simple/test-http-blank-header.js

@ -5,43 +5,43 @@ var net = require('net');
var gotReq = false; var gotReq = false;
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
common.error('got req'); common.error('got req');
gotReq = true; gotReq = true;
assert.equal('GET', req.method); assert.equal('GET', req.method);
assert.equal('/blah', req.url); assert.equal('/blah', req.url);
assert.deepEqual({ assert.deepEqual({
host: "mapdevel.trolologames.ru:443", host: 'mapdevel.trolologames.ru:443',
origin: "http://mapdevel.trolologames.ru", origin: 'http://mapdevel.trolologames.ru',
cookie: "", cookie: ''
}, req.headers); }, req.headers);
}); });
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.addListener('connect', function () { c.addListener('connect', function() {
common.error('client wrote message'); common.error('client wrote message');
c.write( "GET /blah HTTP/1.1\r\n" c.write('GET /blah HTTP/1.1\r\n' +
+ "Host: mapdevel.trolologames.ru:443\r\n" 'Host: mapdevel.trolologames.ru:443\r\n' +
+ "Cookie:\r\n" 'Cookie:\r\n' +
+ "Origin: http://mapdevel.trolologames.ru\r\n" 'Origin: http://mapdevel.trolologames.ru\r\n' +
+ "\r\n\r\nhello world" '\r\n\r\nhello world'
); );
}); });
c.addListener('end', function () { c.addListener('end', function() {
c.end(); c.end();
}); });
c.addListener('close', function () { c.addListener('close', function() {
common.error('client close'); common.error('client close');
server.close(); server.close();
}); });
}); });
process.addListener('exit', function () { process.addListener('exit', function() {
assert.ok(gotReq); assert.ok(gotReq);
}); });

28
test/simple/test-http-buffer-sanity.js

@ -12,15 +12,15 @@ for (var i = 0; i < buffer.length; i++) {
} }
var web = http.Server(function (req, res) { var web = http.Server(function(req, res) {
web.close(); web.close();
console.log(req.headers); console.log(req.headers);
var i = 0; var i = 0;
req.on('data', function (d) { req.on('data', function(d) {
process.stdout.write(","); process.stdout.write(',');
measuredSize += d.length; measuredSize += d.length;
for (var j = 0; j < d.length; j++) { for (var j = 0; j < d.length; j++) {
assert.equal(buffer[i], d[j]); assert.equal(buffer[i], d[j]);
@ -29,40 +29,40 @@ var web = http.Server(function (req, res) {
}); });
req.on('end', function () { req.on('end', function() {
res.writeHead(200); res.writeHead(200);
res.write("thanks"); res.write('thanks');
res.end(); res.end();
console.log("response with 'thanks'"); console.log('response with \'thanks\'');
}); });
req.connection.on('error', function (e) { req.connection.on('error', function(e) {
console.log("http server-side error: " + e.message); console.log('http server-side error: ' + e.message);
process.exit(1); process.exit(1);
}); });
}); });
var gotThanks = false; var gotThanks = false;
web.listen(common.PORT, function () { web.listen(common.PORT, function() {
console.log("Making request"); console.log('Making request');
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req = client.request('GET', '/', { 'content-length': buffer.length }); var req = client.request('GET', '/', { 'content-length': buffer.length });
req.end(buffer); req.end(buffer);
req.on('response', function (res) { req.on('response', function(res) {
console.log('Got response'); console.log('Got response');
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function (string) { res.on('data', function(string) {
assert.equal("thanks", string); assert.equal('thanks', string);
gotThanks = true; gotThanks = true;
}); });
}); });
}); });
process.on('exit', function () { process.on('exit', function() {
assert.equal(bufferSize, measuredSize); assert.equal(bufferSize, measuredSize);
assert.ok(gotThanks); assert.ok(gotThanks);
}); });

29
test/simple/test-http-cat.js

@ -1,13 +1,13 @@
var common = require("../common"); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require("http"); var http = require('http');
var body = "exports.A = function() { return 'A';}"; var body = 'exports.A = function() { return "A";}';
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
console.log("got request"); console.log('got request');
res.writeHead(200, [ res.writeHead(200, [
["Content-Length", body.length], ['Content-Length', body.length],
["Content-Type", "text/plain"] ['Content-Type', 'text/plain']
]); ]);
res.end(body); res.end(body);
}); });
@ -15,28 +15,29 @@ var server = http.createServer(function (req, res) {
var got_good_server_content = false; var got_good_server_content = false;
var bad_server_got_error = false; var bad_server_got_error = false;
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
http.cat("http://localhost:"+common.PORT+"/", "utf8", function (err, content) { http.cat('http://localhost:' + common.PORT + '/', 'utf8',
function(err, content) {
if (err) { if (err) {
throw err; throw err;
} else { } else {
console.log("got response"); console.log('got response');
got_good_server_content = true; got_good_server_content = true;
assert.equal(body, content); assert.equal(body, content);
server.close(); server.close();
} }
}); });
http.cat("http://localhost:12312/", "utf8", function (err, content) { http.cat('http://localhost:12312/', 'utf8', function(err, content) {
if (err) { if (err) {
console.log("got error (this should happen)"); console.log('got error (this should happen)');
bad_server_got_error = true; bad_server_got_error = true;
} }
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
console.log("exit"); console.log('exit');
assert.equal(true, got_good_server_content); assert.equal(true, got_good_server_content);
assert.equal(true, bad_server_got_error); assert.equal(true, bad_server_got_error);
}); });

19
test/simple/test-http-chunked.js

@ -1,17 +1,26 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require("http"); var http = require('http');
var UTF8_STRING = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、经济现状。"; var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' +
'国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' +
'贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' +
'由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' +
'南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' +
'南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' +
'南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' +
'采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' +
'有效的改善了岭南地区落后的政治、经济现状。';
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/plain; charset=utf8"}); res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'});
res.end(UTF8_STRING, 'utf8'); res.end(UTF8_STRING, 'utf8');
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
http.cat("http://127.0.0.1:"+common.PORT+"/", "utf8", function (err, data) { http.cat('http://127.0.0.1:' + common.PORT + '/', 'utf8',
function(err, data) {
if (err) throw err; if (err) throw err;
assert.equal('string', typeof data); assert.equal('string', typeof data);
console.log('here is the response:'); console.log('here is the response:');

12
test/simple/test-http-client-parse-error.js

@ -1,4 +1,4 @@
var common = require("../common"); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
@ -8,21 +8,21 @@ var net = require('net');
var srv = net.createServer(function(c) { var srv = net.createServer(function(c) {
c.write('bad http - should trigger parse error\r\n'); c.write('bad http - should trigger parse error\r\n');
console.log("connection"); console.log('connection');
c.addListener('end', function() { c.end(); }); c.addListener('end', function() { c.end(); });
}); });
var parseError = false; var parseError = false;
srv.listen(common.PORT, '127.0.0.1', function () { srv.listen(common.PORT, '127.0.0.1', function() {
var hc = http.createClient(common.PORT, '127.0.0.1'); var hc = http.createClient(common.PORT, '127.0.0.1');
hc.request('GET', '/').end(); hc.request('GET', '/').end();
hc.on('error', function (e) { hc.on('error', function(e) {
console.log("got error from client"); console.log('got error from client');
srv.close(); srv.close();
assert.ok(e.message.indexOf("Parse Error") >= 0); assert.ok(e.message.indexOf('Parse Error') >= 0);
parseError = true; parseError = true;
}); });
}); });

65
test/simple/test-http-client-race-2.js

@ -1,59 +1,58 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var url = require("url"); var url = require('url');
// //
// Slight variation on test-http-client-race to test for another race // Slight variation on test-http-client-race to test for another race
// condition involving the parsers FreeList used internally by http.Client. // condition involving the parsers FreeList used internally by http.Client.
// //
var body1_s = "1111111111111111"; var body1_s = '1111111111111111';
var body2_s = "22222"; var body2_s = '22222';
var body3_s = "3333333333333333333"; var body3_s = '3333333333333333333';
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
var pathname = url.parse(req.url).pathname; var pathname = url.parse(req.url).pathname;
var body; var body;
switch (pathname) { switch (pathname) {
case "/1": body = body1_s; break; case '/1': body = body1_s; break;
case "/2": body = body2_s; break; case '/2': body = body2_s; break;
default: body = body3_s; default: body = body3_s;
}; }
res.writeHead(200, { "Content-Type": "text/plain" res.writeHead(200,
, "Content-Length": body.length {'Content-Type': 'text/plain', 'Content-Length': body.length});
});
res.end(body); res.end(body);
}); });
server.listen(common.PORT); server.listen(common.PORT);
var body1 = ""; var body1 = '';
var body2 = ""; var body2 = '';
var body3 = ""; var body3 = '';
server.addListener("listening", function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
// //
// Client #1 is assigned Parser #1 // Client #1 is assigned Parser #1
// //
var req1 = client.request("/1") var req1 = client.request('/1');
req1.end(); req1.end();
req1.addListener('response', function (res1) { req1.addListener('response', function(res1) {
res1.setEncoding("utf8"); res1.setEncoding('utf8');
res1.addListener('data', function (chunk) { res1.addListener('data', function(chunk) {
body1 += chunk; body1 += chunk;
}); });
res1.addListener('end', function () { res1.addListener('end', function() {
// //
// Delay execution a little to allow the "close" event to be processed // Delay execution a little to allow the 'close' event to be processed
// (required to trigger this bug!) // (required to trigger this bug!)
// //
setTimeout(function () { setTimeout(function() {
// //
// The bug would introduce itself here: Client #2 would be allocated the // The bug would introduce itself here: Client #2 would be allocated the
// parser that previously belonged to Client #1. But we're not finished // parser that previously belonged to Client #1. But we're not finished
@ -63,24 +62,24 @@ server.addListener("listening", function() {
// //
// At this point, the bug would manifest itself and crash because the // 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. // internal state of the parser was no longer valid for use by Client #1
// //
var req2 = client.request("/2"); var req2 = client.request('/2');
req2.end(); req2.end();
req2.addListener('response', function (res2) { req2.addListener('response', function(res2) {
res2.setEncoding("utf8"); res2.setEncoding('utf8');
res2.addListener('data', function (chunk) { body2 += chunk; }); res2.addListener('data', function(chunk) { body2 += chunk; });
res2.addListener('end', function () { res2.addListener('end', function() {
// //
// Just to be really sure we've covered all our bases, execute a // Just to be really sure we've covered all our bases, execute a
// request using client2. // request using client2.
// //
var req3 = client2.request("/3"); var req3 = client2.request('/3');
req3.end(); req3.end();
req3.addListener('response', function (res3) { req3.addListener('response', function(res3) {
res3.setEncoding("utf8"); res3.setEncoding('utf8');
res3.addListener('data', function (chunk) { body3 += chunk }); res3.addListener('data', function(chunk) { body3 += chunk });
res3.addListener('end', function() { server.close(); }); res3.addListener('end', function() { server.close(); });
}); });
}); });
@ -90,7 +89,7 @@ server.addListener("listening", function() {
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(body1_s, body1); assert.equal(body1_s, body1);
assert.equal(body2_s, body2); assert.equal(body2_s, body2);
assert.equal(body3_s, body3); assert.equal(body3_s, body3);

43
test/simple/test-http-client-race.js

@ -1,48 +1,47 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var url = require("url"); var url = require('url');
var body1_s = "1111111111111111"; var body1_s = '1111111111111111';
var body2_s = "22222"; var body2_s = '22222';
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
var body = url.parse(req.url).pathname === "/1" ? body1_s : body2_s; var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s;
res.writeHead(200, { "Content-Type": "text/plain" res.writeHead(200,
, "Content-Length": body.length {'Content-Type': 'text/plain', 'Content-Length': body.length});
});
res.end(body); res.end(body);
}); });
server.listen(common.PORT); server.listen(common.PORT);
var body1 = ""; var body1 = '';
var body2 = ""; var body2 = '';
server.addListener("listening", function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req1 = client.request("/1") var req1 = client.request('/1');
req1.end(); req1.end();
req1.addListener('response', function (res1) { req1.addListener('response', function(res1) {
res1.setEncoding("utf8"); res1.setEncoding('utf8');
res1.addListener('data', function (chunk) { res1.addListener('data', function(chunk) {
body1 += chunk; body1 += chunk;
}); });
res1.addListener('end', function () { res1.addListener('end', function() {
var req2 = client.request("/2"); var req2 = client.request('/2');
req2.end(); req2.end();
req2.addListener('response', function (res2) { req2.addListener('response', function(res2) {
res2.setEncoding("utf8"); res2.setEncoding('utf8');
res2.addListener('data', function (chunk) { body2 += chunk; }); res2.addListener('data', function(chunk) { body2 += chunk; });
res2.addListener('end', function () { server.close(); }); res2.addListener('end', function() { server.close(); });
}); });
}); });
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(body1_s, body1); assert.equal(body1_s, body1);
assert.equal(body2_s, body2); assert.equal(body2_s, body2);
}); });

24
test/simple/test-http-client-upload.js

@ -2,22 +2,22 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var sent_body = ""; var sent_body = '';
var server_req_complete = false; var server_req_complete = false;
var client_res_complete = false; var client_res_complete = false;
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
assert.equal("POST", req.method); assert.equal('POST', req.method);
req.setEncoding("utf8"); req.setEncoding('utf8');
req.addListener('data', function (chunk) { req.addListener('data', function(chunk) {
console.log("server got: " + JSON.stringify(chunk)); console.log('server got: ' + JSON.stringify(chunk));
sent_body += chunk; sent_body += chunk;
}); });
req.addListener('end', function () { req.addListener('end', function() {
server_req_complete = true; server_req_complete = true;
console.log("request complete from server"); console.log('request complete from server');
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello\n'); res.write('hello\n');
res.end(); res.end();
@ -25,7 +25,7 @@ var server = http.createServer(function(req, res) {
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req = client.request('POST', '/'); var req = client.request('POST', '/');
req.write('1\n'); req.write('1\n');
@ -33,10 +33,10 @@ server.addListener("listening", function() {
req.write('3\n'); req.write('3\n');
req.end(); req.end();
common.error("client finished sending request"); common.error('client finished sending request');
req.addListener('response', function(res) { req.addListener('response', function(res) {
res.setEncoding("utf8"); res.setEncoding('utf8');
res.addListener('data', function(chunk) { res.addListener('data', function(chunk) {
console.log(chunk); console.log(chunk);
}); });
@ -47,8 +47,8 @@ server.addListener("listening", function() {
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal("1\n2\n3\n", sent_body); assert.equal('1\n2\n3\n', sent_body);
assert.equal(true, server_req_complete); assert.equal(true, server_req_complete);
assert.equal(true, client_res_complete); assert.equal(true, client_res_complete);
}); });

11
test/simple/test-http-contentLength0.js

@ -1,12 +1,13 @@
var common = require('../common'); var common = require('../common');
var http = require("http"); var http = require('http');
// Simple test of Node's HTTP Client choking on a response with a "Content-Length: 0 " response header. // Simple test of Node's HTTP Client choking on a response
// I.E. a space character after the "Content-Length" throws an `error` event. // 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) { var s = http.createServer(function(req, res) {
res.writeHead(200, { "Content-Length": "0 " }); res.writeHead(200, {'Content-Length': '0 '});
res.end(); res.end();
}); });
s.listen(common.PORT, function() { s.listen(common.PORT, function() {
@ -14,7 +15,7 @@ s.listen(common.PORT, function() {
var r = http.createClient(common.PORT); var r = http.createClient(common.PORT);
var request = r.request('GET', '/'); var request = r.request('GET', '/');
request.on('response', function (response) { request.on('response', function(response) {
console.log('STATUS: ' + response.statusCode); console.log('STATUS: ' + response.statusCode);
s.close(); s.close();
}); });

19
test/simple/test-http-curl-chunk-problem.js

@ -8,39 +8,40 @@ var http = require('http'),
var filename = require('path').join(common.tmpDir || '/tmp', 'big'); var filename = require('path').join(common.tmpDir || '/tmp', 'big');
var count = 0; var count = 0;
function maybeMakeRequest () { function maybeMakeRequest() {
if (++count < 2) return; if (++count < 2) return;
console.log("making curl request"); console.log('making curl request');
cp.exec('curl http://127.0.0.1:' + common.PORT + '/ | shasum', cp.exec('curl http://127.0.0.1:' + common.PORT + '/ | shasum',
function (err, stdout, stderr) { function(err, stdout, stderr) {
if (err) throw err; if (err) throw err;
assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a', stdout.slice(0, 40)); assert.equal('8c206a1a87599f532ce68675536f0b1546900d7a',
console.log("got the correct response"); stdout.slice(0, 40));
console.log('got the correct response');
server.close(); server.close();
}); });
} }
cp.exec('dd if=/dev/zero of=' + filename + ' bs=1024 count=10240', cp.exec('dd if=/dev/zero of=' + filename + ' bs=1024 count=10240',
function (err, stdout, stderr) { function(err, stdout, stderr) {
if (err) throw err; if (err) throw err;
maybeMakeRequest(); maybeMakeRequest();
}); });
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200); res.writeHead(200);
// Create the subprocess // Create the subprocess
var cat = cp.spawn('cat', [filename]); var cat = cp.spawn('cat', [filename]);
// Stream the data through to the response as binary chunks // Stream the data through to the response as binary chunks
cat.stdout.on('data', function (data) { cat.stdout.on('data', function(data) {
res.write(data); res.write(data);
}); });
// End the response on exit (and log errors) // End the response on exit (and log errors)
cat.on('exit', function (code) { cat.on('exit', function(code) {
if (code !== 0) { if (code !== 0) {
console.error('subprocess exited with code ' + code); console.error('subprocess exited with code ' + code);
exit(1); exit(1);

8
test/simple/test-http-eof-on-connect.js

@ -7,13 +7,13 @@ var http = require('http');
// It is separate from test-http-malformed-request.js because it is only // 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. // reproduceable on the first packet on the first connection to a server.
var server = http.createServer(function (req, res) {}); var server = http.createServer(function(req, res) {});
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
net.createConnection(common.PORT).addListener("connect", function () { net.createConnection(common.PORT).addListener('connect', function() {
this.destroy(); this.destroy();
}).addListener("close", function () { }).addListener('close', function() {
server.close(); server.close();
}); });
}); });

18
test/simple/test-http-exceptions.js

@ -1,17 +1,17 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var http = require('http'); var http = require('http');
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
intentionally_not_defined(); intentionally_not_defined();
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("Thank you, come again."); res.write('Thank you, come again.');
res.end(); res.end();
}); });
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var req; var req;
for (var i = 0; i < 4 ; i += 1) { for (var i = 0; i < 4; i += 1) {
req = http.createClient(common.PORT).request('GET', '/busy/' + i); req = http.createClient(common.PORT).request('GET', '/busy/' + i);
req.end(); req.end();
} }
@ -19,9 +19,9 @@ server.listen(common.PORT, function () {
var exception_count = 0; var exception_count = 0;
process.addListener("uncaughtException", function (err) { process.addListener('uncaughtException', function(err) {
console.log("Caught an exception: " + err); console.log('Caught an exception: ' + err);
if (err.name === "AssertionError") throw err; if (err.name === 'AssertionError') throw err;
if (++exception_count == 4) process.exit(0); if (++exception_count == 4) process.exit(0);
}); });

52
test/simple/test-http-expect-continue.js

@ -1,26 +1,26 @@
var common = require("../common"); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require("http"); var http = require('http');
var outstanding_reqs = 0; var outstanding_reqs = 0;
var test_req_body = "some stuff...\n"; var test_req_body = 'some stuff...\n';
var test_res_body = "other stuff!\n"; var test_res_body = 'other stuff!\n';
var sent_continue = false; var sent_continue = false;
var got_continue = false; var got_continue = false;
function handler(req, res) { function handler(req, res) {
assert.equal(sent_continue, true, "Full response sent before 100 Continue"); assert.equal(sent_continue, true, 'Full response sent before 100 Continue');
common.debug("Server sending full response..."); common.debug('Server sending full response...');
res.writeHead(200, { res.writeHead(200, {
'Content-Type' : 'text/plain', 'Content-Type' : 'text/plain',
"ABCD" : "1" 'ABCD' : '1'
}); });
res.end(test_res_body); res.end(test_res_body);
} }
var server = http.createServer(handler); var server = http.createServer(handler);
server.addListener("checkContinue", function(req, res) { server.addListener('checkContinue', function(req, res) {
common.debug("Server got Expect: 100-continue..."); common.debug('Server got Expect: 100-continue...');
res.writeContinue(); res.writeContinue();
sent_continue = true; sent_continue = true;
handler(req, res); handler(req, res);
@ -29,32 +29,30 @@ server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req = client.request("POST", "/world", { var req = client.request('POST', '/world', {
"Expect": "100-continue", 'Expect': '100-continue'
}); });
common.debug("Client sending request..."); common.debug('Client sending request...');
outstanding_reqs++; outstanding_reqs++;
var body = ""; var body = '';
req.addListener('continue', function () { req.addListener('continue', function() {
common.debug("Client got 100 Continue..."); common.debug('Client got 100 Continue...');
got_continue = true; got_continue = true;
req.end(test_req_body); req.end(test_req_body);
}); });
req.addListener('response', function (res) { req.addListener('response', function(res) {
assert.equal(got_continue, true, assert.equal(got_continue, true,
"Full response received before 100 Continue" 'Full response received before 100 Continue');
);
assert.equal(200, res.statusCode, assert.equal(200, res.statusCode,
"Final status code was " + res.statusCode + ", not 200." 'Final status code was ' + res.statusCode + ', not 200.');
); res.setEncoding('utf8');
res.setEncoding("utf8"); res.addListener('data', function(chunk) { body += chunk; });
res.addListener('data', function (chunk) { body += chunk; }); res.addListener('end', function() {
res.addListener('end', function () { common.debug('Got full response.');
common.debug("Got full response."); assert.equal(body, test_res_body, 'Response body doesn\'t match.');
assert.equal(body, test_res_body, "Response body doesn't match."); assert.ok('abcd' in res.headers, 'Response headers missing.');
assert.ok("abcd" in res.headers, "Response headers missing.");
outstanding_reqs--; outstanding_reqs--;
if (outstanding_reqs == 0) { if (outstanding_reqs == 0) {
server.close(); server.close();

38
test/simple/test-http-full-response.js

@ -1,20 +1,20 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
// This test requires the program "ab" // This test requires the program 'ab'
var http = require('http'); var http = require('http');
var exec = require("child_process").exec; var exec = require('child_process').exec;
var bodyLength = 12345; var bodyLength = 12345;
var body = ""; var body = '';
for (var i = 0; i < bodyLength; i++) { for (var i = 0; i < bodyLength; i++) {
body += 'c'; body += 'c';
} }
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200, { res.writeHead(200, {
"Content-Length": bodyLength, 'Content-Length': bodyLength,
"Content-Type": "text/plain" 'Content-Type': 'text/plain'
}); });
res.end(body); res.end(body);
}); });
@ -22,11 +22,11 @@ var server = http.createServer(function (req, res) {
var runs = 0; var runs = 0;
function runAb(opts, callback) { function runAb(opts, callback) {
var command = "ab " + opts + " http://127.0.0.1:" + common.PORT + "/"; var command = 'ab ' + opts + ' http://127.0.0.1:' + common.PORT + '/';
exec(command, function (err, stdout, stderr) { exec(command, function(err, stdout, stderr) {
if (err) { if (err) {
if (stderr.indexOf("ab") >= 0) { if (stderr.indexOf('ab') >= 0) {
console.log("ab not installed? skipping test.\n" + stderr); console.log('ab not installed? skipping test.\n' + stderr);
process.reallyExit(0); process.reallyExit(0);
} }
process.exit(); process.exit();
@ -47,19 +47,19 @@ function runAb(opts, callback) {
runs++; runs++;
if (callback) callback() if (callback) callback();
}); });
} }
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
runAb("-c 1 -n 10", function () { runAb('-c 1 -n 10', function() {
console.log("-c 1 -n 10 okay"); console.log('-c 1 -n 10 okay');
runAb("-c 1 -n 100", function () { runAb('-c 1 -n 100', function() {
console.log("-c 1 -n 100 okay"); console.log('-c 1 -n 100 okay');
runAb("-c 1 -n 1000", function () { runAb('-c 1 -n 1000', function() {
console.log("-c 1 -n 1000 okay"); console.log('-c 1 -n 1000 okay');
server.close(); server.close();
}); });
}); });
@ -67,6 +67,6 @@ server.listen(common.PORT, function () {
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(3, runs); assert.equal(3, runs);
}); });

16
test/simple/test-http-head-request.js

@ -4,30 +4,30 @@ var http = require('http');
var util = require('util'); var util = require('util');
var body = "hello world\n"; var body = 'hello world\n';
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
common.error('req: ' + req.method); common.error('req: ' + req.method);
res.writeHead(200, {"Content-Length": body.length}); res.writeHead(200, {'Content-Length': body.length});
res.end(); res.end();
server.close(); server.close();
}); });
var gotEnd = false; var gotEnd = false;
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var request = client.request("HEAD", "/"); var request = client.request('HEAD', '/');
request.end(); request.end();
request.addListener('response', function (response) { request.addListener('response', function(response) {
common.error('response start'); common.error('response start');
response.addListener("end", function () { response.addListener('end', function() {
common.error('response end'); common.error('response end');
gotEnd = true; gotEnd = true;
}); });
}); });
}); });
process.addListener('exit', function () { process.addListener('exit', function() {
assert.ok(gotEnd); assert.ok(gotEnd);
}); });

8
test/simple/test-http-head-response-has-no-body.js

@ -15,11 +15,11 @@ server.listen(common.PORT);
var responseComplete = false; var responseComplete = false;
server.addListener("listening", function() { server.addListener('listening', function() {
var req = http.createClient(common.PORT).request('HEAD', '/') var req = http.createClient(common.PORT).request('HEAD', '/');
common.error('req'); common.error('req');
req.end(); req.end();
req.addListener('response', function (res) { req.addListener('response', function(res) {
common.error('response'); common.error('response');
res.addListener('end', function() { res.addListener('end', function() {
common.error('response end'); common.error('response end');
@ -29,6 +29,6 @@ server.addListener("listening", function() {
}); });
}); });
process.addListener('exit', function () { process.addListener('exit', function() {
assert.ok(responseComplete); assert.ok(responseComplete);
}); });

34
test/simple/test-http-keep-alive-close-on-header.js

@ -3,45 +3,45 @@ var assert = require('assert');
var http = require('http'); var http = require('http');
var util = require('util'); var util = require('util');
var body = "hello world\n"; var body = 'hello world\n';
var headers = {'connection':'keep-alive'} var headers = {'connection': 'keep-alive'};
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Length": body.length, "Connection":"close"}); res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'});
res.write(body); res.write(body);
res.end(); res.end();
}); });
var connectCount = 0; var connectCount = 0;
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
client.addListener("connect", function () { client.addListener('connect', function() {
common.error("CONNECTED") common.error('CONNECTED');
connectCount++; connectCount++;
}) });
var request = client.request("GET", "/", headers); var request = client.request('GET', '/', headers);
request.end(); request.end();
request.addListener('response', function (response) { request.addListener('response', function(response) {
common.error('response start'); common.error('response start');
response.addListener("end", function () { response.addListener('end', function() {
common.error('response end'); common.error('response end');
var req = client.request("GET", "/", headers); var req = client.request('GET', '/', headers);
req.addListener('response', function (response) { req.addListener('response', function(response) {
response.addListener("end", function () { response.addListener('end', function() {
client.end(); client.end();
server.close(); server.close();
}) });
}) });
req.end(); req.end();
}); });
}); });
}); });
process.addListener('exit', function () { process.addListener('exit', function() {
assert.equal(2, connectCount); assert.equal(2, connectCount);
}); });

35
test/simple/test-http-keep-alive.js

@ -3,45 +3,44 @@ var assert = require('assert');
var http = require('http'); var http = require('http');
var util = require('util'); var util = require('util');
var body = "hello world\n"; var body = 'hello world\n';
var headers = {'connection':'keep-alive'} var headers = {'connection': 'keep-alive'};
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Length": body.length}); res.writeHead(200, {'Content-Length': body.length});
res.write(body); res.write(body);
res.end(); res.end();
}); });
var connectCount = 0; var connectCount = 0;
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
client.addListener("connect", function () { client.addListener('connect', function() {
common.error("CONNECTED") common.error('CONNECTED');
connectCount++; connectCount++;
}) });
var request = client.request("GET", "/", headers); var request = client.request('GET', '/', headers);
request.end(); request.end();
request.addListener('response', function (response) { request.addListener('response', function(response) {
common.error('response start'); common.error('response start');
response.addListener('end', function() {
response.addListener("end", function () {
common.error('response end'); common.error('response end');
var req = client.request("GET", "/", headers); var req = client.request('GET', '/', headers);
req.addListener('response', function (response) { req.addListener('response', function(response) {
response.addListener("end", function () { response.addListener('end', function() {
client.end(); client.end();
server.close(); server.close();
}) });
}) });
req.end(); req.end();
}); });
}); });
}); });
process.addListener('exit', function () { process.addListener('exit', function() {
assert.equal(1, connectCount); assert.equal(1, connectCount);
}); });

18
test/simple/test-http-malformed-request.js

@ -2,7 +2,7 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var net = require('net'); var net = require('net');
var http = require('http'); var http = require('http');
var url = require("url"); var url = require('url');
// Make sure no exceptions are thrown when receiving malformed HTTP // Make sure no exceptions are thrown when receiving malformed HTTP
// requests. // requests.
@ -10,27 +10,27 @@ var url = require("url");
var nrequests_completed = 0; var nrequests_completed = 0;
var nrequests_expected = 1; var nrequests_expected = 1;
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
console.log("req: " + JSON.stringify(url.parse(req.url))); console.log('req: ' + JSON.stringify(url.parse(req.url)));
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("Hello World"); res.write('Hello World');
res.end(); res.end();
if (++nrequests_completed == nrequests_expected) server.close(); if (++nrequests_completed == nrequests_expected) server.close();
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.addListener("connect", function () { c.addListener('connect', function() {
c.write("GET /hello?foo=%99bar HTTP/1.1\r\n\r\n"); c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n');
c.end(); c.end();
}); });
// TODO add more! // TODO add more!
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(nrequests_expected, nrequests_completed); assert.equal(nrequests_expected, nrequests_completed);
}); });

32
test/simple/test-http-parser.js

@ -8,39 +8,39 @@ var assert = require('assert');
var HTTPParser = process.binding('http_parser').HTTPParser; var HTTPParser = process.binding('http_parser').HTTPParser;
var parser = new HTTPParser("request"); var parser = new HTTPParser('request');
var Buffer = require('buffer').Buffer; var Buffer = require('buffer').Buffer;
var buffer = new Buffer(1024); var buffer = new Buffer(1024);
var request = "GET /hello HTTP/1.1\r\n\r\n"; var request = 'GET /hello HTTP/1.1\r\n\r\n';
buffer.write(request, 0, 'ascii'); buffer.write(request, 0, 'ascii');
var callbacks = 0; var callbacks = 0;
parser.onMessageBegin = function () { parser.onMessageBegin = function() {
console.log("message begin"); console.log('message begin');
callbacks++; callbacks++;
}; };
parser.onHeadersComplete = function (info) { parser.onHeadersComplete = function(info) {
console.log("headers complete: " + JSON.stringify(info)); console.log('headers complete: ' + JSON.stringify(info));
assert.equal('GET', info.method); assert.equal('GET', info.method);
assert.equal(1, info.versionMajor); assert.equal(1, info.versionMajor);
assert.equal(1, info.versionMinor); assert.equal(1, info.versionMinor);
callbacks++; callbacks++;
}; };
parser.onURL = function (b, off, len) { parser.onURL = function(b, off, len) {
//throw new Error("hello world"); //throw new Error('hello world');
callbacks++; callbacks++;
}; };
parser.onPath = function (b, off, length) { parser.onPath = function(b, off, length) {
console.log("path [" + off + ", " + length + "]"); console.log('path [' + off + ', ' + length + ']');
var path = b.toString('ascii', off, off+length); var path = b.toString('ascii', off, off + length);
console.log("path = '" + path + "'"); console.log('path = "' + path + '"');
assert.equal('/hello', path); assert.equal('/hello', path);
callbacks++; callbacks++;
}; };
@ -53,11 +53,11 @@ assert.equal(4, callbacks);
// thrown from parser.execute() // thrown from parser.execute()
// //
parser.onURL = function (b, off, len) { parser.onURL = function(b, off, len) {
throw new Error("hello world"); throw new Error('hello world');
}; };
assert.throws(function () { assert.throws(function() {
parser.execute(buffer, 0, request.length); parser.execute(buffer, 0, request.length);
}, Error, "hello world"); }, Error, 'hello world');

62
test/simple/test-http-proxy.js

@ -1,33 +1,35 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var url = require("url"); var url = require('url');
var PROXY_PORT = common.PORT; var PROXY_PORT = common.PORT;
var BACKEND_PORT = common.PORT+1; var BACKEND_PORT = common.PORT + 1;
var cookies = [ "session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT", var cookies = [
"prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" ]; '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", var headers = {'content-type': 'text/plain',
"set-cookie": cookies, 'set-cookie': cookies,
"hello": "world" }; 'hello': 'world' };
var backend = http.createServer(function (req, res) { var backend = http.createServer(function(req, res) {
common.debug("backend request"); common.debug('backend request');
res.writeHead(200, headers); res.writeHead(200, headers);
res.write("hello world\n"); res.write('hello world\n');
res.end(); res.end();
}); });
var proxy_client = http.createClient(BACKEND_PORT); var proxy_client = http.createClient(BACKEND_PORT);
var proxy = http.createServer(function (req, res) { var proxy = http.createServer(function(req, res) {
common.debug("proxy req headers: " + JSON.stringify(req.headers)); common.debug('proxy req headers: ' + JSON.stringify(req.headers));
var proxy_req = proxy_client.request(url.parse(req.url).pathname); var proxy_req = proxy_client.request(url.parse(req.url).pathname);
proxy_req.end(); proxy_req.end();
proxy_req.addListener('response', function(proxy_res) { proxy_req.addListener('response', function(proxy_res) {
common.debug("proxy res headers: " + JSON.stringify(proxy_res.headers)); common.debug('proxy res headers: ' + JSON.stringify(proxy_res.headers));
assert.equal('world', proxy_res.headers['hello']); assert.equal('world', proxy_res.headers['hello']);
assert.equal('text/plain', proxy_res.headers['content-type']); assert.equal('text/plain', proxy_res.headers['content-type']);
@ -35,52 +37,52 @@ var proxy = http.createServer(function (req, res) {
res.writeHead(proxy_res.statusCode, proxy_res.headers); res.writeHead(proxy_res.statusCode, proxy_res.headers);
proxy_res.addListener("data", function(chunk) { proxy_res.addListener('data', function(chunk) {
res.write(chunk); res.write(chunk);
}); });
proxy_res.addListener("end", function() { proxy_res.addListener('end', function() {
res.end(); res.end();
common.debug("proxy res"); common.debug('proxy res');
}); });
}); });
}); });
var body = ""; var body = '';
var nlistening = 0; var nlistening = 0;
function startReq () { function startReq() {
nlistening++; nlistening++;
if (nlistening < 2) return; if (nlistening < 2) return;
var client = http.createClient(PROXY_PORT); var client = http.createClient(PROXY_PORT);
var req = client.request("/test"); var req = client.request('/test');
common.debug("client req") common.debug('client req');
req.addListener('response', function (res) { req.addListener('response', function(res) {
common.debug("got res"); common.debug('got res');
assert.equal(200, res.statusCode); assert.equal(200, res.statusCode);
assert.equal('world', res.headers['hello']); assert.equal('world', res.headers['hello']);
assert.equal('text/plain', res.headers['content-type']); assert.equal('text/plain', res.headers['content-type']);
assert.deepEqual(cookies, res.headers['set-cookie']); assert.deepEqual(cookies, res.headers['set-cookie']);
res.setEncoding("utf8"); res.setEncoding('utf8');
res.addListener('data', function (chunk) { body += chunk; }); res.addListener('data', function(chunk) { body += chunk; });
res.addListener('end', function () { res.addListener('end', function() {
proxy.close(); proxy.close();
backend.close(); backend.close();
common.debug("closed both"); common.debug('closed both');
}); });
}); });
req.end(); req.end();
} }
common.debug("listen proxy") common.debug('listen proxy');
proxy.listen(PROXY_PORT, startReq); proxy.listen(PROXY_PORT, startReq);
common.debug("listen backend") common.debug('listen backend');
backend.listen(BACKEND_PORT, startReq); backend.listen(BACKEND_PORT, startReq);
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(body, "hello world\n"); assert.equal(body, 'hello world\n');
}); });

5
test/simple/test-http-server-multiheaders.js

@ -18,7 +18,7 @@ var srv = http.createServer(function(req, res) {
srv.close(); srv.close();
}); });
srv.listen(common.PORT, function () { srv.listen(common.PORT, function() {
var hc = http.createClient(common.PORT, 'localhost'); var hc = http.createClient(common.PORT, 'localhost');
var hr = hc.request('/', var hr = hc.request('/',
[ [
@ -31,7 +31,6 @@ srv.listen(common.PORT, function () {
['x-foo', 'bingo'], ['x-foo', 'bingo'],
['x-bar', 'banjo'], ['x-bar', 'banjo'],
['x-bar', 'bango'] ['x-bar', 'bango']
] ]);
);
hr.end(); hr.end();
}); });

66
test/simple/test-http-server.js

@ -2,45 +2,45 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var net = require('net'); var net = require('net');
var http = require('http'); var http = require('http');
var url = require("url"); var url = require('url');
var qs = require("querystring"); var qs = require('querystring');
var request_number = 0; var request_number = 0;
var requests_sent = 0; var requests_sent = 0;
var server_response = ""; var server_response = '';
var client_got_eof = false; var client_got_eof = false;
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.id = request_number; res.id = request_number;
req.id = request_number++; req.id = request_number++;
if (req.id == 0) { if (req.id == 0) {
assert.equal("GET", req.method); assert.equal('GET', req.method);
assert.equal("/hello", url.parse(req.url).pathname); assert.equal('/hello', url.parse(req.url).pathname);
assert.equal("world", qs.parse(url.parse(req.url).query).hello); assert.equal('world', qs.parse(url.parse(req.url).query).hello);
assert.equal("b==ar", qs.parse(url.parse(req.url).query).foo); assert.equal('b==ar', qs.parse(url.parse(req.url).query).foo);
} }
if (req.id == 1) { if (req.id == 1) {
common.error("req 1"); common.error('req 1');
assert.equal("POST", req.method); assert.equal('POST', req.method);
assert.equal("/quit", url.parse(req.url).pathname); assert.equal('/quit', url.parse(req.url).pathname);
} }
if (req.id == 2) { if (req.id == 2) {
common.error("req 2"); common.error('req 2');
assert.equal("foo", req.headers['x-x']); assert.equal('foo', req.headers['x-x']);
} }
if (req.id == 3) { if (req.id == 3) {
common.error("req 3"); common.error('req 3');
assert.equal("bar", req.headers['x-x']); assert.equal('bar', req.headers['x-x']);
this.close(); this.close();
common.error("server closed"); common.error('server closed');
} }
setTimeout(function () { setTimeout(function() {
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(url.parse(req.url).pathname); res.write(url.parse(req.url).pathname);
res.end(); res.end();
}, 1); }, 1);
@ -48,51 +48,51 @@ var server = http.createServer(function (req, res) {
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.setEncoding("utf8"); c.setEncoding('utf8');
c.addListener("connect", function () { c.addListener('connect', function() {
c.write( "GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n" ); c.write('GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n');
requests_sent += 1; requests_sent += 1;
}); });
c.addListener("data", function (chunk) { c.addListener('data', function(chunk) {
server_response += chunk; server_response += chunk;
if (requests_sent == 1) { if (requests_sent == 1) {
c.write("POST /quit HTTP/1.1\r\n\r\n"); c.write('POST /quit HTTP/1.1\r\n\r\n');
requests_sent += 1; requests_sent += 1;
} }
if (requests_sent == 2) { if (requests_sent == 2) {
c.write("GET / HTTP/1.1\r\nX-X: foo\r\n\r\n" 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"); 'GET / HTTP/1.1\r\nX-X: bar\r\n\r\n');
c.end(); c.end();
assert.equal(c.readyState, "readOnly"); assert.equal(c.readyState, 'readOnly');
requests_sent += 2; requests_sent += 2;
} }
}); });
c.addListener("end", function () { c.addListener('end', function() {
client_got_eof = true; client_got_eof = true;
}); });
c.addListener("close", function () { c.addListener('close', function() {
assert.equal(c.readyState, "closed"); assert.equal(c.readyState, 'closed');
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(4, request_number); assert.equal(4, request_number);
assert.equal(4, requests_sent); assert.equal(4, requests_sent);
var hello = new RegExp("/hello"); var hello = new RegExp('/hello');
assert.equal(true, hello.exec(server_response) != null); assert.equal(true, hello.exec(server_response) != null);
var quit = new RegExp("/quit"); var quit = new RegExp('/quit');
assert.equal(true, quit.exec(server_response) != null); assert.equal(true, quit.exec(server_response) != null);
assert.equal(true, client_got_eof); assert.equal(true, client_got_eof);

18
test/simple/test-http-set-cookies.js

@ -1,24 +1,24 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var http = require('http'); var http = require('http');
var nresponses = 0; var nresponses = 0;
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
if (req.url == '/one') { if (req.url == '/one') {
res.writeHead(200, [ ['set-cookie', 'A'], res.writeHead(200, [['set-cookie', 'A'],
['content-type', 'text/plain'] ]); ['content-type', 'text/plain']]);
res.end("one\n"); res.end('one\n');
} else { } else {
res.writeHead(200, [ ['set-cookie', 'A'], res.writeHead(200, [['set-cookie', 'A'],
['set-cookie', 'B'], ['set-cookie', 'B'],
['content-type', 'text/plain'] ]); ['content-type', 'text/plain']]);
res.end("two\n"); res.end('two\n');
} }
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
// //
// one set-cookie header // one set-cookie header
// //
@ -66,6 +66,6 @@ server.addListener("listening", function() {
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(2, nresponses); assert.equal(2, nresponses);
}); });

17
test/simple/test-http-set-timeout.js

@ -1,25 +1,26 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert');; var assert = require('assert');
var http = require('http'); var http = require('http');
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
console.log('got request. setting 1 second timeout'); console.log('got request. setting 1 second timeout');
req.connection.setTimeout(500); req.connection.setTimeout(500);
req.connection.addListener('timeout', function(){ req.connection.addListener('timeout', function() {
common.debug("TIMEOUT"); common.debug('TIMEOUT');
server.close(); server.close();
}); });
}); });
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
console.log('Server running at http://127.0.0.1:'+common.PORT+'/'); console.log('Server running at http://127.0.0.1:' + common.PORT + '/');
var errorTimer = setTimeout(function () { var errorTimer = setTimeout(function() {
throw new Error('Timeout was not sucessful'); throw new Error('Timeout was not sucessful');
}, 2000); }, 2000);
http.cat('http://localhost:'+common.PORT+'/', 'utf8', function (err, content) { http.cat('http://localhost:' + common.PORT + '/', 'utf8',
function(err, content) {
clearTimeout(errorTimer); clearTimeout(errorTimer);
console.log('HTTP REQUEST COMPLETE (this is good)'); console.log('HTTP REQUEST COMPLETE (this is good)');
}); });

53
test/simple/test-http-set-trailers.js

@ -6,33 +6,33 @@ var net = require('net');
var outstanding_reqs = 0; var outstanding_reqs = 0;
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200, [ ['content-type', 'text/plain'] ]); res.writeHead(200, [['content-type', 'text/plain']]);
res.addTrailers({"x-foo": "bar"}); res.addTrailers({'x-foo': 'bar'});
res.end("stuff" + "\n"); res.end('stuff' + '\n');
}); });
server.listen(common.PORT); server.listen(common.PORT);
// first, we test an HTTP/1.0 request. // first, we test an HTTP/1.0 request.
server.addListener("listening", function() { server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
var res_buffer = ""; var res_buffer = '';
c.setEncoding("utf8"); c.setEncoding('utf8');
c.addListener("connect", function () { c.addListener('connect', function() {
outstanding_reqs++; outstanding_reqs++;
c.write( "GET / HTTP/1.0\r\n\r\n" ); c.write('GET / HTTP/1.0\r\n\r\n');
}); });
c.addListener("data", function (chunk) { c.addListener('data', function(chunk) {
// console.log(chunk); //console.log(chunk);
res_buffer += chunk; res_buffer += chunk;
}); });
c.addListener("end", function () { c.addListener('end', function() {
c.end(); c.end();
assert.ok(! /x-foo/.test(res_buffer), "Trailer in HTTP/1.0 response."); assert.ok(! /x-foo/.test(res_buffer), 'Trailer in HTTP/1.0 response.');
outstanding_reqs--; outstanding_reqs--;
if (outstanding_reqs == 0) { if (outstanding_reqs == 0) {
server.close(); server.close();
@ -42,28 +42,28 @@ server.addListener("listening", function() {
}); });
// now, we test an HTTP/1.1 request. // now, we test an HTTP/1.1 request.
server.addListener("listening", function() { server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
var res_buffer = ""; var res_buffer = '';
var tid; var tid;
c.setEncoding("utf8"); c.setEncoding('utf8');
c.addListener("connect", function () { c.addListener('connect', function() {
outstanding_reqs++; outstanding_reqs++;
c.write( "GET / HTTP/1.1\r\n\r\n" ); c.write('GET / HTTP/1.1\r\n\r\n');
tid = setTimeout(assert.fail, 2000, "Couldn't find last chunk."); tid = setTimeout(assert.fail, 2000, 'Couldn\'t find last chunk.');
}); });
c.addListener("data", function (chunk) { c.addListener('data', function(chunk) {
// console.log(chunk); //console.log(chunk);
res_buffer += chunk; res_buffer += chunk;
if (/0\r\n/.test(res_buffer)) { // got the end. if (/0\r\n/.test(res_buffer)) { // got the end.
outstanding_reqs--; outstanding_reqs--;
clearTimeout(tid); clearTimeout(tid);
assert.ok( assert.ok(
/0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer), /0\r\nx-foo: bar\r\n\r\n$/.test(res_buffer),
"No trailer in HTTP/1.1 response." 'No trailer in HTTP/1.1 response.'
); );
if (outstanding_reqs == 0) { if (outstanding_reqs == 0) {
server.close(); server.close();
@ -76,14 +76,13 @@ server.addListener("listening", function() {
// now, see if the client sees the trailers. // now, see if the client sees the trailers.
server.addListener('listening', function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req = client.request("/hello", {}); var req = client.request('/hello', {});
req.end(); req.end();
outstanding_reqs++; outstanding_reqs++;
req.addListener('response', function (res) { req.addListener('response', function(res) {
res.addListener('end', function () { res.addListener('end', function() {
// console.log(res.trailers); //console.log(res.trailers);
assert.ok("x-foo" in res.trailers, assert.ok('x-foo' in res.trailers, 'Client doesn\'t see trailers.');
"Client doesn't see trailers.");
outstanding_reqs--; outstanding_reqs--;
if (outstanding_reqs == 0) { if (outstanding_reqs == 0) {
server.close(); server.close();

8
test/simple/test-http-upgrade-client.js

@ -29,7 +29,7 @@ var srv = net.createServer(function(c) {
var gotUpgrade = false; var gotUpgrade = false;
srv.listen(common.PORT, '127.0.0.1', function () { srv.listen(common.PORT, '127.0.0.1', function() {
var hc = http.createClient(common.PORT, '127.0.0.1'); var hc = http.createClient(common.PORT, '127.0.0.1');
hc.addListener('upgrade', function(res, socket, upgradeHead) { hc.addListener('upgrade', function(res, socket, upgradeHead) {
@ -38,9 +38,9 @@ srv.listen(common.PORT, '127.0.0.1', function () {
assert.equal(upgradeHead, 'nurtzo'); assert.equal(upgradeHead, 'nurtzo');
console.log(res.headers); console.log(res.headers);
var expectedHeaders = { "hello": "world", var expectedHeaders = {'hello': 'world',
"connection": "upgrade", 'connection': 'upgrade',
"upgrade": "websocket" }; 'upgrade': 'websocket' };
assert.deepEqual(expectedHeaders, res.headers); assert.deepEqual(expectedHeaders, res.headers);
socket.end(); socket.end();

8
test/simple/test-http-upgrade-client2.js

@ -1,4 +1,4 @@
var common = require("../common"); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
@ -9,14 +9,14 @@ server.on('upgrade', function(req, socket, head) {
socket.write('HTTP/1.1 101 Ok' + CRLF + socket.write('HTTP/1.1 101 Ok' + CRLF +
'Connection: Upgrade' + CRLF + 'Connection: Upgrade' + CRLF +
'Upgrade: Test' + CRLF + CRLF + 'head'); 'Upgrade: Test' + CRLF + CRLF + 'head');
socket.on('end', function () { socket.on('end', function() {
socket.end(); socket.end();
}); });
}); });
var successCount = 0; var successCount = 0;
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
@ -61,6 +61,6 @@ server.listen(common.PORT, function () {
}); });
process.on('exit', function () { process.on('exit', function() {
assert.equal(2, successCount); assert.equal(2, successCount);
}); });

125
test/simple/test-http-upgrade-server.js

@ -1,149 +1,154 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var util = require("util"); var util = require('util');
var net = require("net"); var net = require('net');
var http = require("http"); var http = require('http');
var requests_recv = 0; var requests_recv = 0;
var requests_sent = 0; var requests_sent = 0;
var request_upgradeHead = null; var request_upgradeHead = null;
function createTestServer(){ function createTestServer() {
return new testServer(); return new testServer();
}; }
function testServer(){ function testServer() {
var server = this; var server = this;
http.Server.call(server, function(){}); http.Server.call(server, function() {});
server.addListener("connection", function(){ server.addListener('connection', function() {
requests_recv++; requests_recv++;
}); });
server.addListener("request", function(req, res){ server.addListener('request', function(req, res) {
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("okay"); res.write('okay');
res.end(); res.end();
}); });
server.addListener("upgrade", function(req, socket, upgradeHead){ server.addListener('upgrade', function(req, socket, upgradeHead) {
socket.write("HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
"Upgrade: WebSocket\r\n" + 'Upgrade: WebSocket\r\n' +
"Connection: Upgrade\r\n" + 'Connection: Upgrade\r\n' +
"\r\n\r\n"); '\r\n\r\n');
request_upgradeHead = upgradeHead; request_upgradeHead = upgradeHead;
socket.ondata = function(d, start, end){ socket.ondata = function(d, start, end) {
var data = d.toString('utf8', start, end); var data = d.toString('utf8', start, end);
if(data == "kill"){ if (data == 'kill') {
socket.end(); socket.end();
} else { } else {
socket.write(data, "utf8"); socket.write(data, 'utf8');
} }
}; };
}); });
}; }
util.inherits(testServer, http.Server); util.inherits(testServer, http.Server);
function writeReq(socket, data, encoding){ function writeReq(socket, data, encoding) {
requests_sent++; requests_sent++;
socket.write(data); socket.write(data);
}; }
/*----------------------------------------------- /*-----------------------------------------------
connection: Upgrade with listener connection: Upgrade with listener
-----------------------------------------------*/ -----------------------------------------------*/
function test_upgrade_with_listener(_server){ function test_upgrade_with_listener(_server) {
var conn = net.createConnection(common.PORT); var conn = net.createConnection(common.PORT);
conn.setEncoding("utf8"); conn.setEncoding('utf8');
var state = 0; var state = 0;
conn.addListener("connect", function () { conn.addListener('connect', function() {
writeReq(conn, "GET / HTTP/1.1\r\n" + writeReq(conn,
"Upgrade: WebSocket\r\n" + 'GET / HTTP/1.1\r\n' +
"Connection: Upgrade\r\n" + 'Upgrade: WebSocket\r\n' +
"\r\n" + 'Connection: Upgrade\r\n' +
"WjN}|M(6"); '\r\n' +
'WjN}|M(6');
}); });
conn.addListener("data", function (data) { conn.addListener('data', function(data) {
state++; state++;
assert.equal('string', typeof data); assert.equal('string', typeof data);
if(state == 1) { if (state == 1) {
assert.equal("HTTP/1.1 101", data.substr(0, 12)); assert.equal('HTTP/1.1 101', data.substr(0, 12));
assert.equal("WjN}|M(6", request_upgradeHead.toString("utf8")); assert.equal('WjN}|M(6', request_upgradeHead.toString('utf8'));
conn.write("test", "utf8"); conn.write('test', 'utf8');
} else if(state == 2) { } else if (state == 2) {
assert.equal("test", data); assert.equal('test', data);
conn.write("kill", "utf8"); conn.write('kill', 'utf8');
} }
}); });
conn.addListener("end", function(){ conn.addListener('end', function() {
assert.equal(2, state); assert.equal(2, state);
conn.end(); conn.end();
_server.removeAllListeners("upgrade"); _server.removeAllListeners('upgrade');
test_upgrade_no_listener(); test_upgrade_no_listener();
}); });
}; }
/*----------------------------------------------- /*-----------------------------------------------
connection: Upgrade, no listener connection: Upgrade, no listener
-----------------------------------------------*/ -----------------------------------------------*/
var test_upgrade_no_listener_ended = false; var test_upgrade_no_listener_ended = false;
function test_upgrade_no_listener(){ function test_upgrade_no_listener() {
var conn = net.createConnection(common.PORT); var conn = net.createConnection(common.PORT);
conn.setEncoding("utf8"); conn.setEncoding('utf8');
conn.addListener("connect", function () { conn.addListener('connect', function() {
writeReq(conn, "GET / HTTP/1.1\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\n\r\n"); writeReq(conn,
'GET / HTTP/1.1\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
}); });
conn.addListener("end", function(){ conn.addListener('end', function() {
test_upgrade_no_listener_ended = true; test_upgrade_no_listener_ended = true;
conn.end(); conn.end();
}); });
conn.addListener("close", function(){ conn.addListener('close', function() {
test_standard_http(); test_standard_http();
}); });
}; }
/*----------------------------------------------- /*-----------------------------------------------
connection: normal connection: normal
-----------------------------------------------*/ -----------------------------------------------*/
function test_standard_http(){ function test_standard_http() {
var conn = net.createConnection(common.PORT); var conn = net.createConnection(common.PORT);
conn.setEncoding("utf8"); conn.setEncoding('utf8');
conn.addListener("connect", function () { conn.addListener('connect', function() {
writeReq(conn, "GET / HTTP/1.1\r\n\r\n"); writeReq(conn, 'GET / HTTP/1.1\r\n\r\n');
}); });
conn.addListener("data", function(data){ conn.addListener('data', function(data) {
assert.equal("string", typeof data); assert.equal('string', typeof data);
assert.equal("HTTP/1.1 200", data.substr(0, 12)); assert.equal('HTTP/1.1 200', data.substr(0, 12));
conn.end(); conn.end();
}); });
conn.addListener("close", function(){ conn.addListener('close', function() {
server.close(); server.close();
}); });
}; }
var server = createTestServer(); var server = createTestServer();
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
// All tests get chained after this: // All tests get chained after this:
test_upgrade_with_listener(server); test_upgrade_with_listener(server);
}); });
@ -152,7 +157,7 @@ server.listen(common.PORT, function () {
/*----------------------------------------------- /*-----------------------------------------------
Fin. Fin.
-----------------------------------------------*/ -----------------------------------------------*/
process.addListener("exit", function () { process.addListener('exit', function() {
assert.equal(3, requests_recv); assert.equal(3, requests_recv);
assert.equal(3, requests_sent); assert.equal(3, requests_sent);
assert.ok(test_upgrade_no_listener_ended); assert.ok(test_upgrade_no_listener_ended);

28
test/simple/test-http-upgrade-server2.js

@ -3,12 +3,12 @@ var assert = require('assert');
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
common.error('got req'); common.error('got req');
throw new Error("This shouldn't happen."); throw new Error('This shouldn\'t happen.');
}); });
server.addListener('upgrade', function (req, socket, upgradeHead) { server.addListener('upgrade', function(req, socket, upgradeHead) {
common.error('got upgrade event'); common.error('got upgrade event');
// test that throwing an error from upgrade gets // test that throwing an error from upgrade gets
// is uncaught // is uncaught
@ -17,35 +17,35 @@ server.addListener('upgrade', function (req, socket, upgradeHead) {
var gotError = false; var gotError = false;
process.addListener('uncaughtException', function (e) { process.addListener('uncaughtException', function(e) {
common.error('got "clientError" event'); common.error('got \'clientError\' event');
assert.equal('upgrade error', e.message); assert.equal('upgrade error', e.message);
gotError = true; gotError = true;
process.exit(0); process.exit(0);
}); });
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.addListener('connect', function () { c.addListener('connect', function() {
common.error('client wrote message'); common.error('client wrote message');
c.write("GET /blah HTTP/1.1\r\n" + c.write('GET /blah HTTP/1.1\r\n' +
"Upgrade: WebSocket\r\n" + 'Upgrade: WebSocket\r\n' +
"Connection: Upgrade\r\n" + 'Connection: Upgrade\r\n' +
"\r\n\r\nhello world"); '\r\n\r\nhello world');
}); });
c.addListener('end', function () { c.addListener('end', function() {
c.end(); c.end();
}); });
c.addListener('close', function () { c.addListener('close', function() {
common.error('client close'); common.error('client close');
server.close(); server.close();
}); });
}); });
process.addListener('exit', function () { process.addListener('exit', function() {
assert.ok(gotError); assert.ok(gotError);
}); });

32
test/simple/test-http-wget.js

@ -18,49 +18,49 @@ var http = require('http');
// content-length is not provided, that the connection is in fact // content-length is not provided, that the connection is in fact
// closed. // closed.
var server_response = ""; var server_response = '';
var client_got_eof = false; var client_got_eof = false;
var connection_was_closed = false; var connection_was_closed = false;
var server = http.createServer(function (req, res) { var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("hello "); res.write('hello ');
res.write("world\n"); res.write('world\n');
res.end(); res.end();
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var c = net.createConnection(common.PORT); var c = net.createConnection(common.PORT);
c.setEncoding("utf8"); c.setEncoding('utf8');
c.addListener("connect", function () { c.addListener('connect', function() {
c.write("GET / HTTP/1.0\r\n" + c.write('GET / HTTP/1.0\r\n' +
"Connection: Keep-Alive\r\n\r\n"); 'Connection: Keep-Alive\r\n\r\n');
}); });
c.addListener("data", function (chunk) { c.addListener('data', function(chunk) {
console.log(chunk); console.log(chunk);
server_response += chunk; server_response += chunk;
}); });
c.addListener("end", function () { c.addListener('end', function() {
client_got_eof = true; client_got_eof = true;
console.log('got end'); console.log('got end');
c.end(); c.end();
}); });
c.addListener("close", function () { c.addListener('close', function() {
connection_was_closed = true; connection_was_closed = true;
console.log('got close'); console.log('got close');
server.close(); server.close();
}); });
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
var m = server_response.split("\r\n\r\n"); var m = server_response.split('\r\n\r\n');
assert.equal(m[1], "hello world\n"); assert.equal(m[1], 'hello world\n');
assert.ok(client_got_eof); assert.ok(client_got_eof);
assert.ok(connection_was_closed); assert.ok(connection_was_closed);
}); });

20
test/simple/test-http-write-empty-string.js

@ -3,7 +3,7 @@ var assert = require('assert');
var http = require('http'); var http = require('http');
var server = http.createServer(function (request, response) { var server = http.createServer(function(request, response) {
console.log('responding to ' + request.url); console.log('responding to ' + request.url);
response.writeHead(200, {'Content-Type': 'text/plain'}); response.writeHead(200, {'Content-Type': 'text/plain'});
@ -14,26 +14,26 @@ var server = http.createServer(function (request, response) {
response.end('3\n'); response.end('3\n');
this.close(); this.close();
}) });
var response=""; var response = '';
process.addListener('exit', function () { process.addListener('exit', function() {
assert.equal('1\n2\n3\n', response); assert.equal('1\n2\n3\n', response);
}); });
server.listen(common.PORT, function () { server.listen(common.PORT, function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req = client.request("/"); var req = client.request('/');
req.end(); req.end();
req.addListener('response', function (res) { req.addListener('response', function(res) {
assert.equal(200, res.statusCode); assert.equal(200, res.statusCode);
res.setEncoding("ascii"); res.setEncoding('ascii');
res.addListener('data', function (chunk) { res.addListener('data', function(chunk) {
response += chunk; response += chunk;
}); });
common.error("Got /hello response"); common.error('Got /hello response');
}); });
}); });

68
test/simple/test-http.js

@ -1,80 +1,80 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var url = require("url"); var url = require('url');
function p (x) { function p(x) {
common.error(common.inspect(x)); common.error(common.inspect(x));
} }
var responses_sent = 0; var responses_sent = 0;
var responses_recvd = 0; var responses_recvd = 0;
var body0 = ""; var body0 = '';
var body1 = ""; var body1 = '';
var server = http.Server(function (req, res) { var server = http.Server(function(req, res) {
if (responses_sent == 0) { if (responses_sent == 0) {
assert.equal("GET", req.method); assert.equal('GET', req.method);
assert.equal("/hello", url.parse(req.url).pathname); assert.equal('/hello', url.parse(req.url).pathname);
console.dir(req.headers); console.dir(req.headers);
assert.equal(true, "accept" in req.headers); assert.equal(true, 'accept' in req.headers);
assert.equal("*/*", req.headers["accept"]); assert.equal('*/*', req.headers['accept']);
assert.equal(true, "foo" in req.headers); assert.equal(true, 'foo' in req.headers);
assert.equal("bar", req.headers["foo"]); assert.equal('bar', req.headers['foo']);
} }
if (responses_sent == 1) { if (responses_sent == 1) {
assert.equal("POST", req.method); assert.equal('POST', req.method);
assert.equal("/world", url.parse(req.url).pathname); assert.equal('/world', url.parse(req.url).pathname);
this.close(); this.close();
} }
req.addListener('end', function () { req.addListener('end', function() {
res.writeHead(200, {"Content-Type": "text/plain"}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("The path was " + url.parse(req.url).pathname); res.write('The path was ' + url.parse(req.url).pathname);
res.end(); res.end();
responses_sent += 1; responses_sent += 1;
}); });
//assert.equal("127.0.0.1", res.connection.remoteAddress); //assert.equal('127.0.0.1', res.connection.remoteAddress);
}); });
server.listen(common.PORT); server.listen(common.PORT);
server.addListener("listening", function() { server.addListener('listening', function() {
var client = http.createClient(common.PORT); var client = http.createClient(common.PORT);
var req = client.request("/hello", {"Accept": "*/*", "Foo": "bar"}); var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'});
req.end(); req.end();
req.addListener('response', function (res) { req.addListener('response', function(res) {
assert.equal(200, res.statusCode); assert.equal(200, res.statusCode);
responses_recvd += 1; responses_recvd += 1;
res.setEncoding("utf8"); res.setEncoding('utf8');
res.addListener('data', function (chunk) { body0 += chunk; }); res.addListener('data', function(chunk) { body0 += chunk; });
common.debug("Got /hello response"); common.debug('Got /hello response');
}); });
setTimeout(function () { setTimeout(function() {
req = client.request("POST", "/world"); req = client.request('POST', '/world');
req.end(); req.end();
req.addListener('response',function (res) { req.addListener('response', function(res) {
assert.equal(200, res.statusCode); assert.equal(200, res.statusCode);
responses_recvd += 1; responses_recvd += 1;
res.setEncoding("utf8"); res.setEncoding('utf8');
res.addListener('data', function (chunk) { body1 += chunk; }); res.addListener('data', function(chunk) { body1 += chunk; });
common.debug("Got /world response"); common.debug('Got /world response');
}); });
}, 1); }, 1);
}); });
process.addListener("exit", function () { process.addListener('exit', function() {
common.debug("responses_recvd: " + responses_recvd); common.debug('responses_recvd: ' + responses_recvd);
assert.equal(2, responses_recvd); assert.equal(2, responses_recvd);
common.debug("responses_sent: " + responses_sent); common.debug('responses_sent: ' + responses_sent);
assert.equal(2, responses_sent); assert.equal(2, responses_sent);
assert.equal("The path was /hello", body0); assert.equal('The path was /hello', body0);
assert.equal("The path was /world", body1); assert.equal('The path was /world', body1);
}); });

114
test/simple/test-path.js

@ -42,74 +42,78 @@ assert.equal(path.extname('file.'), '.');
var failures = []; var failures = [];
var joinTests = var joinTests =
// arguments result // arguments result
[[['.', 'x/b', '..', '/b/c.js' ], 'x/b/c.js' ] [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'],
,[['/.', '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', '../../../bar'], '../../bar'],
,[['foo/', '../../../bar' ], '../../bar' ] [['foo/', '../../../bar'], '../../bar'],
,[['foo/x', '../../../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/x/', './bar'], 'foo/x/bar'],
,[['foo/x/', '.', 'bar' ], 'foo/x/bar' ] [['foo/x/', '.', 'bar'], 'foo/x/bar'],
,[['./' ], './' ] [['./'], './'],
,[['.', './' ], './' ] [['.', './'], './'],
,[['.', '.', '.' ], '.' ] [['.', '.', '.'], '.'],
,[['.', './', '.' ], '.' ] [['.', './', '.'], '.'],
,[['.', '/./', '.' ], '.' ] [['.', '/./', '.'], '.'],
,[['.', '/////./', '.' ], '.' ] [['.', '/////./', '.'], '.'],
,[['.' ], '.' ] [['.'], '.'],
,[['','.' ], '.' ] [['', '.'], '.'],
,[['', 'foo' ], 'foo' ] [['', 'foo'], 'foo'],
,[['foo', '/bar' ], 'foo/bar' ] [['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', '', '/bar' ], 'foo/bar' ] [['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'],
,[[' ', '.' ], ' ' ] [[' ', '.'], ' '],
,[[' ', '/' ], ' /' ] [[' ', '/'], ' /'],
,[[' ', '' ], ' ' ] [[' ', ''], ' '],
// preserving empty path parts, for url resolution case // preserving empty path parts, for url resolution case
// pass boolean true as LAST argument. // pass boolean true as LAST argument.
,[['', '', true ], '/' ] [['', '', true], '/'],
,[['foo', '', true ], 'foo/' ] [['foo', '', true], 'foo/'],
,[['foo', '', 'bar', true ], 'foo//bar' ] [['foo', '', 'bar', true], 'foo//bar'],
,[['foo/', '', 'bar', true ], 'foo///bar' ] [['foo/', '', 'bar', true], 'foo///bar'],
,[['', true ], '.' ] [['', true], '.'],
// filtration of non-strings. // filtration of non-strings.
,[['x', true, 7, 'y', null, {} ], 'x/y' ] [['x', true, 7, 'y', null, {}], 'x/y']
]; ];
joinTests.forEach(function(test) { joinTests.forEach(function(test) {
var actual = path.join.apply(path, test[0]); var actual = path.join.apply(path, test[0]);
var expected = test[1]; var expected = test[1];
var message = 'path.join('+test[0].map(JSON.stringify).join(',')+')' var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' +
+ '\n expect='+JSON.stringify(expected) '\n expect=' + JSON.stringify(expected) +
+ '\n actual='+JSON.stringify(actual); '\n actual=' + JSON.stringify(actual);
if (actual !== expected) failures.push('\n'+message); if (actual !== expected) failures.push('\n' + message);
// assert.equal(actual, expected, message); // assert.equal(actual, expected, message);
}); });
assert.equal(failures.length, 0, failures.join('')) assert.equal(failures.length, 0, failures.join(''));
assert.equal(path.normalize('./fixtures///b/../b/c.js'), 'fixtures/b/c.js'); assert.equal(path.normalize('./fixtures///b/../b/c.js'),
assert.equal(path.normalize('./fixtures///b/../b/c.js',true), 'fixtures///b/c.js'); 'fixtures/b/c.js');
assert.equal(path.normalize('./fixtures///b/../b/c.js', true),
'fixtures///b/c.js');
assert.equal(path.normalize('/foo/../../../bar'), '/bar'); assert.equal(path.normalize('/foo/../../../bar'), '/bar');
assert.deepEqual(path.normalizeArray(['fixtures','b','','..','b','c.js']), ['fixtures','b','c.js']); assert.deepEqual(path.normalizeArray(['fixtures', 'b', '', '..', 'b', 'c.js']),
assert.deepEqual(path.normalizeArray(['fixtures','','b','..','b','c.js'], true), ['fixtures','','b','c.js']); ['fixtures', 'b', 'c.js']);
assert.deepEqual(path.normalizeArray(['fixtures', '', 'b', '..', 'b', 'c.js'],
true), ['fixtures', '', 'b', 'c.js']);
assert.equal(path.normalize('a//b//../b', true), 'a//b/b'); assert.equal(path.normalize('a//b//../b', true), 'a//b/b');
assert.equal(path.normalize('a//b//../b'), 'a/b'); assert.equal(path.normalize('a//b//../b'), 'a/b');

615
test/simple/test-url.js

@ -7,163 +7,163 @@ var url = require('url'),
// URLs to parse, and expected data // URLs to parse, and expected data
// { url : parsed } // { url : parsed }
var parseTests = { var parseTests = {
"//some_path" : { '//some_path' : {
"href": "//some_path", 'href': '//some_path',
"pathname": "//some_path" 'pathname': '//some_path'
}, },
"http://www.narwhaljs.org/blog/categories?id=news" : { 'http://www.narwhaljs.org/blog/categories?id=news' : {
"href": "http://www.narwhaljs.org/blog/categories?id=news", 'href': 'http://www.narwhaljs.org/blog/categories?id=news',
"protocol": "http:", 'protocol': 'http:',
"host": "www.narwhaljs.org", 'host': 'www.narwhaljs.org',
"hostname": "www.narwhaljs.org", 'hostname': 'www.narwhaljs.org',
"search": "?id=news", 'search': '?id=news',
"query": "id=news", 'query': 'id=news',
"pathname": "/blog/categories" 'pathname': '/blog/categories'
}, },
"http://mt0.google.com/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=", 'href': 'http://mt0.google.com/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=',
"protocol": "http:", 'protocol': 'http:',
"host": "mt0.google.com", 'host': 'mt0.google.com',
"hostname": "mt0.google.com", 'hostname': 'mt0.google.com',
"pathname": "/vt/lyrs=m@114&hl=en&src=api&x=2&y=2&z=3&s=" 'pathname': '/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=" : { '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=", 'href': 'http://mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=',
"protocol": "http:", 'protocol': 'http:',
"host": "mt0.google.com", 'host': 'mt0.google.com',
"hostname": "mt0.google.com", 'hostname': 'mt0.google.com',
"search": "???&hl=en&src=api&x=2&y=2&z=3&s=", 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=',
"query": "??&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" 'pathname': '/vt/lyrs=m@114'
}, },
"http://user:pass@mt0.google.com/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=", 'href': 'http://user:pass@mt0.google.com/vt/lyrs=m@114???&hl=en&src=api&x=2&y=2&z=3&s=',
"protocol": "http:", 'protocol': 'http:',
"host": "user:pass@mt0.google.com", 'host': 'user:pass@mt0.google.com',
"auth": "user:pass", 'auth': 'user:pass',
"hostname": "mt0.google.com", 'hostname': 'mt0.google.com',
"search": "???&hl=en&src=api&x=2&y=2&z=3&s=", 'search': '???&hl=en&src=api&x=2&y=2&z=3&s=',
"query": "??&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" 'pathname': '/vt/lyrs=m@114'
}, },
"file:///etc/passwd" : { 'file:///etc/passwd' : {
"href": "file:///etc/passwd", 'href': 'file:///etc/passwd',
"protocol": "file:", 'protocol': 'file:',
"pathname": "///etc/passwd" 'pathname': '///etc/passwd'
}, },
"file:///etc/node/" : { 'file:///etc/node/' : {
"href": "file:///etc/node/", 'href': 'file:///etc/node/',
"protocol": "file:", 'protocol': 'file:',
"pathname": "///etc/node/" 'pathname': '///etc/node/'
}, },
"http:/baz/../foo/bar" : { 'http:/baz/../foo/bar' : {
"href": "http:/baz/../foo/bar", 'href': 'http:/baz/../foo/bar',
"protocol": "http:", 'protocol': 'http:',
"pathname": "/baz/../foo/bar" 'pathname': '/baz/../foo/bar'
}, },
"http://user:pass@example.com:8000/foo/bar?baz=quux#frag" : { 'http://user:pass@example.com:8000/foo/bar?baz=quux#frag' : {
"href": "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:", 'protocol': 'http:',
"host": "user:pass@example.com:8000", 'host': 'user:pass@example.com:8000',
"auth": "user:pass", 'auth': 'user:pass',
"port": "8000", 'port': '8000',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag", 'hash': '#frag',
"search": "?baz=quux", 'search': '?baz=quux',
"query": "baz=quux", 'query': 'baz=quux',
"pathname": "/foo/bar" 'pathname': '/foo/bar'
}, },
"//user:pass@example.com:8000/foo/bar?baz=quux#frag" : { '//user:pass@example.com:8000/foo/bar?baz=quux#frag' : {
"href": "//user:pass@example.com:8000/foo/bar?baz=quux#frag", 'href': '//user:pass@example.com:8000/foo/bar?baz=quux#frag',
"host": "user:pass@example.com:8000", 'host': 'user:pass@example.com:8000',
"auth": "user:pass", 'auth': 'user:pass',
"port": "8000", 'port': '8000',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag", 'hash': '#frag',
"search": "?baz=quux", 'search': '?baz=quux',
"query": "baz=quux", 'query': 'baz=quux',
"pathname": "/foo/bar" 'pathname': '/foo/bar'
}, },
"http://example.com?foo=bar#frag" : { 'http://example.com?foo=bar#frag' : {
"href": "http://example.com?foo=bar#frag", 'href': 'http://example.com?foo=bar#frag',
"protocol": "http:", 'protocol': 'http:',
"host": "example.com", 'host': 'example.com',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag", 'hash': '#frag',
"search": "?foo=bar", 'search': '?foo=bar',
"query": "foo=bar" 'query': 'foo=bar'
}, },
"http://example.com?foo=@bar#frag" : { 'http://example.com?foo=@bar#frag' : {
"href": "http://example.com?foo=@bar#frag", 'href': 'http://example.com?foo=@bar#frag',
"protocol": "http:", 'protocol': 'http:',
"host": "example.com", 'host': 'example.com',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag", 'hash': '#frag',
"search": "?foo=@bar", 'search': '?foo=@bar',
"query": "foo=@bar" 'query': 'foo=@bar'
}, },
"http://example.com?foo=/bar/#frag" : { 'http://example.com?foo=/bar/#frag' : {
"href": "http://example.com?foo=/bar/#frag", 'href': 'http://example.com?foo=/bar/#frag',
"protocol": "http:", 'protocol': 'http:',
"host": "example.com", 'host': 'example.com',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag", 'hash': '#frag',
"search": "?foo=/bar/", 'search': '?foo=/bar/',
"query": "foo=/bar/" 'query': 'foo=/bar/'
}, },
"http://example.com?foo=?bar/#frag" : { 'http://example.com?foo=?bar/#frag' : {
"href": "http://example.com?foo=?bar/#frag", 'href': 'http://example.com?foo=?bar/#frag',
"protocol": "http:", 'protocol': 'http:',
"host": "example.com", 'host': 'example.com',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag", 'hash': '#frag',
"search": "?foo=?bar/", 'search': '?foo=?bar/',
"query": "foo=?bar/" 'query': 'foo=?bar/'
}, },
"http://example.com#frag=?bar/#frag" : { 'http://example.com#frag=?bar/#frag' : {
"href": "http://example.com#frag=?bar/#frag", 'href': 'http://example.com#frag=?bar/#frag',
"protocol": "http:", 'protocol': 'http:',
"host": "example.com", 'host': 'example.com',
"hostname": "example.com", 'hostname': 'example.com',
"hash": "#frag=?bar/#frag" 'hash': '#frag=?bar/#frag'
}, },
"/foo/bar?baz=quux#frag" : { '/foo/bar?baz=quux#frag' : {
"href": "/foo/bar?baz=quux#frag", 'href': '/foo/bar?baz=quux#frag',
"hash": "#frag", 'hash': '#frag',
"search": "?baz=quux", 'search': '?baz=quux',
"query": "baz=quux", 'query': 'baz=quux',
"pathname": "/foo/bar" 'pathname': '/foo/bar'
}, },
"http:/foo/bar?baz=quux#frag" : { 'http:/foo/bar?baz=quux#frag' : {
"href": "http:/foo/bar?baz=quux#frag", 'href': 'http:/foo/bar?baz=quux#frag',
"protocol": "http:", 'protocol': 'http:',
"hash": "#frag", 'hash': '#frag',
"search": "?baz=quux", 'search': '?baz=quux',
"query": "baz=quux", 'query': 'baz=quux',
"pathname": "/foo/bar" 'pathname': '/foo/bar'
}, },
"mailto:foo@bar.com?subject=hello" : { 'mailto:foo@bar.com?subject=hello' : {
"href": "mailto:foo@bar.com?subject=hello", 'href': 'mailto:foo@bar.com?subject=hello',
"protocol": "mailto:", 'protocol': 'mailto:',
"host": "foo@bar.com", 'host': 'foo@bar.com',
"auth" : "foo", 'auth' : 'foo',
"hostname" : "bar.com", 'hostname' : 'bar.com',
"search": "?subject=hello", 'search': '?subject=hello',
"query": "subject=hello" 'query': 'subject=hello'
}, },
"javascript:alert('hello');" : { 'javascript:alert(\'hello\');' : {
"href": "javascript:alert('hello');", 'href': 'javascript:alert(\'hello\');',
"protocol": "javascript:", 'protocol': 'javascript:',
"host": "alert('hello')", 'host': 'alert(\'hello\')',
"hostname": "alert('hello')", 'hostname': 'alert(\'hello\')',
"pathname" : ";" 'pathname' : ';'
}, },
"xmpp:isaacschlueter@jabber.org" : { 'xmpp:isaacschlueter@jabber.org' : {
"href": "xmpp:isaacschlueter@jabber.org", 'href': 'xmpp:isaacschlueter@jabber.org',
"protocol": "xmpp:", 'protocol': 'xmpp:',
"host": "isaacschlueter@jabber.org", 'host': 'isaacschlueter@jabber.org',
"auth": "isaacschlueter", 'auth': 'isaacschlueter',
"hostname": "jabber.org" 'hostname': 'jabber.org'
} }
}; };
for (var u in parseTests) { for (var u in parseTests) {
@ -172,86 +172,108 @@ for (var u in parseTests) {
for (var i in expected) { for (var i in expected) {
var e = JSON.stringify(expected[i]), var e = JSON.stringify(expected[i]),
a = JSON.stringify(actual[i]); a = JSON.stringify(actual[i]);
assert.equal(e, a, "parse(" + u + ")."+i+" == "+e+"\nactual: "+a); assert.equal(e, a,
'parse(' + u + ').' + i + ' == ' + e + '\nactual: ' + a);
} }
var expected = u, var expected = u,
actual = url.format(parseTests[u]); actual = url.format(parseTests[u]);
assert.equal(expected, actual, "format("+u+") == "+u+"\nactual:"+actual); assert.equal(expected, actual,
'format(' + u + ') == ' + u + '\nactual:' + actual);
} }
var parseTestsWithQueryString = { var parseTestsWithQueryString = {
"/foo/bar?baz=quux#frag" : { '/foo/bar?baz=quux#frag' : {
"href": "/foo/bar?baz=quux#frag", 'href': '/foo/bar?baz=quux#frag',
"hash": "#frag", 'hash': '#frag',
"search": "?baz=quux", 'search': '?baz=quux',
"query": { 'query': {
"baz": "quux" 'baz': 'quux'
},
"pathname": "/foo/bar"
}, },
'pathname': '/foo/bar'
}
}; };
for (var u in parseTestsWithQueryString) { for (var u in parseTestsWithQueryString) {
var actual = url.parse(u,true); var actual = url.parse(u, true);
var expected = parseTestsWithQueryString[u]; var expected = parseTestsWithQueryString[u];
for (var i in expected) { for (var i in expected) {
var e = JSON.stringify(expected[i]), var e = JSON.stringify(expected[i]),
a = JSON.stringify(actual[i]); a = JSON.stringify(actual[i]);
assert.equal(e, a, "parse(" + u + ")."+i+" == "+e+"\nactual: "+a); assert.equal(e, a,
'parse(' + u + ').' + i + ' == ' + e + '\nactual: ' + a);
} }
} }
// some extra formatting tests, just to verify that it'll format slightly wonky content to a valid url. // some extra formatting tests, just to verify
// that it'll format slightly wonky content to a valid url.
var formatTests = { var formatTests = {
"http://a.com/a/b/c?s#h" : { 'http://a.com/a/b/c?s#h' : {
"protocol": "http", 'protocol': 'http',
"host": "a.com", 'host': 'a.com',
"pathname": "a/b/c", 'pathname': 'a/b/c',
"hash": "h", 'hash': 'h',
"search": "s" 'search': 's'
}, },
"xmpp:isaacschlueter@jabber.org" : { 'xmpp:isaacschlueter@jabber.org' : {
"href": "xmpp://isaacschlueter@jabber.org", 'href': 'xmpp://isaacschlueter@jabber.org',
"protocol": "xmpp:", 'protocol': 'xmpp:',
"host": "isaacschlueter@jabber.org", 'host': 'isaacschlueter@jabber.org',
"auth": "isaacschlueter", 'auth': 'isaacschlueter',
"hostname": "jabber.org" 'hostname': 'jabber.org'
} }
}; };
for (var u in formatTests) { for (var u in formatTests) {
var actual = url.format(formatTests[u]); var actual = url.format(formatTests[u]);
assert.equal(actual, u, "wonky format("+u+") == "+u+"\nactual:"+actual); assert.equal(actual, u,
'wonky format(' + u + ') == ' + u + '\nactual:' + actual);
} }
[ /*
// [from, path, expected] [from, path, expected]
["/foo/bar/baz", "quux", "/foo/bar/quux"], */
["/foo/bar/baz", "quux/asdf", "/foo/bar/quux/asdf"], var relativeTests = [
["/foo/bar/baz", "quux/baz", "/foo/bar/quux/baz"], ['/foo/bar/baz', 'quux', '/foo/bar/quux'],
["/foo/bar/baz", "../quux/baz", "/foo/quux/baz"], ['/foo/bar/baz', 'quux/asdf', '/foo/bar/quux/asdf'],
["/foo/bar/baz", "/bar", "/bar"], ['/foo/bar/baz', 'quux/baz', '/foo/bar/quux/baz'],
["/foo/bar/baz/", "quux", "/foo/bar/baz/quux"], ['/foo/bar/baz', '../quux/baz', '/foo/quux/baz'],
["/foo/bar/baz/", "quux/baz", "/foo/bar/baz/quux/baz"], ['/foo/bar/baz', '/bar', '/bar'],
["/foo/bar/baz", "../../../../../../../../quux/baz", "/quux/baz"], ['/foo/bar/baz/', 'quux', '/foo/bar/baz/quux'],
["/foo/bar/baz", "../../../../../../../quux/baz", "/quux/baz"], ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'],
["foo/bar", "../../../baz", "../../baz"], ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'],
["foo/bar/", "../../../baz", "../baz"], ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'],
["http://example.com/b//c//d;p?q#blarg","https:#hash2","https:///#hash2" ], ['foo/bar', '../../../baz', '../../baz'],
["http://example.com/b//c//d;p?q#blarg","https:/p/a/t/h?s#hash2","https://p/a/t/h?s#hash2" ], ['foo/bar/', '../../../baz', '../baz'],
["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:#hash2', 'https:///#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://example.com/b//c//d;p?q#blarg","http:#hash2","http://example.com/b//c//d;p?q#hash2" ], 'https:/p/a/t/h?s#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" ], 'https://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://example.com/b//c//d;p?q#blarg","http:/a/b/c/d","http://example.com/a/b/c/d"], 'https://u:p@h.com/p/a/t/h?s#hash2',
["/foo/bar/baz", "/../etc/passwd", "/etc/passwd"] 'https://u:p@h.com/p/a/t/h?s#hash2'],
].forEach(function (relativeTest) { ['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]), var a = url.resolve(relativeTest[0], relativeTest[1]),
e = relativeTest[2]; e = relativeTest[2];
assert.equal(e, a, assert.equal(e, a,
"resolve("+[relativeTest[0], relativeTest[1]]+") == "+e+ 'resolve(' + [relativeTest[0], relativeTest[1]] + ') == ' + e +
"\n actual="+a); '\n actual=' + a);
}); });
@ -273,50 +295,51 @@ var bases = [
]; ];
//[to, from, result] //[to, from, result]
[ var relativeTests2 = [
// http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html // http://lists.w3.org/Archives/Public/uri/2004Feb/0114.html
['../c', 'foo:a/b', 'foo:c'], ['../c', 'foo:a/b', 'foo:c'],
['foo:.', 'foo:a', 'foo:'], ['foo:.', 'foo:a', 'foo:'],
['/foo/../../../bar', 'zz:abc', 'zz:/bar'], ['/foo/../../../bar', 'zz:abc', 'zz:/bar'],
['/foo/../bar', 'zz:abc', 'zz:/bar'], ['/foo/../bar', 'zz:abc', 'zz:/bar'],
['foo/../../../bar', 'zz:abc', 'zz:bar'], // @isaacs Disagree. Not how web browsers resolve this. // @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'], // @isaacs Added
['foo/../bar', 'zz:abc', 'zz:bar'], ['foo/../bar', 'zz:abc', 'zz:bar'],
['zz:.', 'zz:abc', 'zz:'], ['zz:.', 'zz:abc', 'zz:'],
['/.' , bases[0], 'http://a/'], ['/.', bases[0], 'http://a/'],
['/.foo' , bases[0], 'http://a/.foo'], ['/.foo', bases[0], 'http://a/.foo'],
['.foo' , bases[0], 'http://a/b/c/.foo'], ['.foo', bases[0], 'http://a/b/c/.foo'],
// http://gbiv.com/protocols/uri/test/rel_examples1.html // http://gbiv.com/protocols/uri/test/rel_examples1.html
// examples from RFC 2396 // examples from RFC 2396
['g:h' , bases[0], 'g:h'], ['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/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://a/g'],
['//g' , bases[0], 'http://g'], ['//g', bases[0], 'http://g'],
// changed with RFC 2396bis // changed with RFC 2396bis
//('?y' , bases[0], 'http://a/b/c/d;p?y'], //('?y', bases[0], 'http://a/b/c/d;p?y'],
['?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'], ['g?y', bases[0], 'http://a/b/c/g?y'],
// changed with RFC 2396bis // changed with RFC 2396bis
//('#s' , bases[0], CURRENT_DOC_URI + '#s'], //('#s', bases[0], CURRENT_DOC_URI + '#s'],
['#s' , bases[0], 'http://a/b/c/d;p?q#s'], ['#s', bases[0], 'http://a/b/c/d;p?q#s'],
['g#s' , bases[0], 'http://a/b/c/g#s'], ['g#s', bases[0], 'http://a/b/c/g#s'],
['g?y#s' , bases[0], 'http://a/b/c/g?y#s'], ['g?y#s', bases[0], 'http://a/b/c/g?y#s'],
[';x' , bases[0], 'http://a/b/c/;x'], [';x', bases[0], 'http://a/b/c/;x'],
['g;x' , bases[0], 'http://a/b/c/g;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'], ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'],
// changed with RFC 2396bis // changed with RFC 2396bis
//('' , bases[0], CURRENT_DOC_URI], //('', bases[0], CURRENT_DOC_URI],
['' , bases[0], 'http://a/b/c/d;p?q'], ['', 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/c/'], ['./', bases[0], 'http://a/b/c/'],
['..' , bases[0], 'http://a/b/'], ['..', bases[0], 'http://a/b/'],
['../' , bases[0], 'http://a/b/'], ['../', bases[0], 'http://a/b/'],
['../g' , bases[0], 'http://a/b/g'], ['../g', bases[0], 'http://a/b/g'],
['../..' , bases[0], 'http://a/'], ['../..', bases[0], 'http://a/'],
['../../' , bases[0], 'http://a/'], ['../../', bases[0], 'http://a/'],
['../../g' , bases[0], 'http://a/g'], ['../../g' , bases[0], 'http://a/g'],
['../../../g', bases[0], ('http://a/../g', 'http://a/g')], ['../../../g', bases[0], ('http://a/../g', 'http://a/g')],
['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')],
@ -347,82 +370,85 @@ var bases = [
// http://gbiv.com/protocols/uri/test/rel_examples2.html // http://gbiv.com/protocols/uri/test/rel_examples2.html
// slashes in base URI's query args // 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/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://a/g'],
['//g' , bases[1], 'http://g'], ['//g', bases[1], 'http://g'],
// changed in RFC 2396bis // changed in RFC 2396bis
//('?y' , bases[1], 'http://a/b/c/?y'], //('?y', bases[1], 'http://a/b/c/?y'],
['?y' , bases[1], 'http://a/b/c/d;p?y'], ['?y', bases[1], 'http://a/b/c/d;p?y'],
['g?y' , bases[1], 'http://a/b/c/g?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?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', 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'],
['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/c/'],
['../' , bases[1], 'http://a/b/'], ['../', bases[1], 'http://a/b/'],
['../g' , bases[1], 'http://a/b/g'], ['../g', bases[1], 'http://a/b/g'],
['../../' , bases[1], 'http://a/'], ['../../', bases[1], 'http://a/'],
['../../g' , bases[1], 'http://a/g'], ['../../g' , bases[1], 'http://a/g'],
// http://gbiv.com/protocols/uri/test/rel_examples3.html // http://gbiv.com/protocols/uri/test/rel_examples3.html
// slashes in path params // slashes in path params
// all of these changed in RFC 2396bis // 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', 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'], ['g?y', bases[2], 'http://a/b/c/d;p=1/g?y'],
[';x' , bases[2], 'http://a/b/c/d;p=1/;x'], [';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', 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/g;x=1/y'],
['g;x=1/../y', bases[2], 'http://a/b/c/d;p=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/d;p=1/'],
['../' , bases[2], 'http://a/b/c/'], ['../', bases[2], 'http://a/b/c/'],
['../g' , bases[2], 'http://a/b/c/g'], ['../g', bases[2], 'http://a/b/c/g'],
['../../' , bases[2], 'http://a/b/'], ['../../', bases[2], 'http://a/b/'],
['../../g' , bases[2], 'http://a/b/g'], ['../../g' , bases[2], 'http://a/b/g'],
// http://gbiv.com/protocols/uri/test/rel_examples4.html // http://gbiv.com/protocols/uri/test/rel_examples4.html
// double and triple slash, unknown scheme // double and triple slash, unknown scheme
['g:h' , bases[3], 'g:h'], ['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:///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//a/g
['//g' , bases[3], 'fred://g'], // may change to fred:///s//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/x', bases[3], 'fred://g/x'], // may change to fred:///s//g/x
['///g' , bases[3], 'fred:///g'], ['///g', bases[3], 'fred:///g'],
['./' , bases[3], 'fred:///s//a/b/'], ['./', bases[3], 'fred:///s//a/b/'],
['../' , bases[3], 'fred:///s//a/'], ['../', bases[3], 'fred:///s//a/'],
['../g' , bases[3], 'fred:///s//a/g'], ['../g', bases[3], 'fred:///s//a/g'],
['../../' , bases[3], 'fred:///s//'], ['../../', bases[3], 'fred:///s//'],
['../../g' , bases[3], 'fred:///s//g'], ['../../g' , bases[3], 'fred:///s//g'],
['../../../g', bases[3], 'fred:///s/g'], ['../../../g', bases[3], 'fred:///s/g'],
['../../../../g', bases[3], 'fred:///g'], // may change to fred:///s//a/../../../g // may change to fred:///s//a/../../../g
['../../../../g', bases[3], 'fred:///g'],
// http://gbiv.com/protocols/uri/test/rel_examples5.html // http://gbiv.com/protocols/uri/test/rel_examples5.html
// double and triple slash, well-known scheme // double and triple slash, well-known scheme
['g:h' , bases[4], 'g:h'], ['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:///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//a/g
['//g' , bases[4], 'http://g'], // may change to http:///s//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/x', bases[4], 'http://g/x'], // may change to http:///s//g/x
['///g' , bases[4], 'http:///g'], ['///g', bases[4], 'http:///g'],
['./' , bases[4], 'http:///s//a/b/'], ['./', bases[4], 'http:///s//a/b/'],
['../' , bases[4], 'http:///s//a/'], ['../', bases[4], 'http:///s//a/'],
['../g' , bases[4], 'http:///s//a/g'], ['../g', bases[4], 'http:///s//a/g'],
['../../' , bases[4], 'http:///s//'], ['../../', bases[4], 'http:///s//'],
['../../g' , bases[4], 'http:///s//g'], ['../../g' , bases[4], 'http:///s//g'],
['../../../g', bases[4], 'http:///s/g'], // may change to http:///s//a/../../g // may change to http:///s//a/../../g
['../../../../g', bases[4], 'http:///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 // from Dan Connelly's tests in http://www.w3.org/2000/10/swap/uripath.py
["bar:abc", "foo:xyz", "bar:abc"], ['bar:abc', 'foo:xyz', 'bar:abc'],
['../abc', 'http://example/x/y/z', 'http://example/x/abc'], ['../abc', 'http://example/x/y/z', 'http://example/x/abc'],
['http://example/x/abc', 'http://example2/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'], ['../r', 'http://ex/x/y/z', 'http://ex/x/r'],
@ -434,7 +460,9 @@ var bases = [
['', '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'], ['', 'http://ex/x/y/pdq', 'http://ex/x/y/pdq'],
['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'], ['z/', 'http://ex/x/y/', 'http://ex/x/y/z/'],
['#Animal', 'file:/swap/test/animal.rdf', 'file:/swap/test/animal.rdf#Animal'], ['#Animal',
'file:/swap/test/animal.rdf',
'file:/swap/test/animal.rdf#Animal'],
['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'], ['../abc', 'file:/e/x/y/z', 'file:/e/x/abc'],
['/example/x/abc', 'file:/example2/x/y/z', 'file:/example/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:/ex/x/r'],
@ -448,12 +476,16 @@ var bases = [
['', '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'], ['', 'file:/ex/x/y/pdq', 'file:/ex/x/y/pdq'],
['z/', 'file:/ex/x/y/', 'file:/ex/x/y/z/'], ['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://meetings.example.com/cal#m1', 'file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', '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'], ['./#blort', 'file:/some/dir/foo', 'file:/some/dir/#blort'],
['./#', 'file:/some/dir/foo', 'file:/some/dir/#'], ['./#', 'file:/some/dir/foo', 'file:/some/dir/#'],
// Ryan Lee // Ryan Lee
["./", "http://example/x/abc.efg", "http://example/x/"], ['./', 'http://example/x/abc.efg', 'http://example/x/'],
// Graham Klyne's tests // Graham Klyne's tests
@ -465,8 +497,12 @@ var bases = [
['./p=q:r', 'http://ex/x/y', 'http://ex/x/p=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'], ['?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'], ['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'], ['local/qual@domain.org#frag',
['more/qual2@domain2.org#frag', 'mailto:local/qual1@domain1.org', 'mailto:local/more/qual2@domain2.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'], ['y?q', 'http://ex/x/y?q', 'http://ex/x/y?q'],
['/x/y?q', 'http://ex?p', '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:a/c/d'],
@ -494,8 +530,12 @@ var bases = [
// 70-77 // 70-77
['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'], ['local2@domain2', 'mailto:local1@domain1?query1', 'mailto:local2@domain2'],
['local2@domain2?query2', 'mailto:local1@domain1', 'mailto:local2@domain2?query2'], ['local2@domain2?query2',
['local2@domain2?query2', 'mailto:local1@domain1?query1', 'mailto: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'], ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'],
['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'], ['local@domain?query2', 'mailto:?query1', 'mailto:local@domain?query2'],
['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'], ['?query2', 'mailto:local@domain?query1', 'mailto:local@domain?query2'],
@ -503,19 +543,26 @@ var bases = [
['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 // 82-88
// ['http:this', 'http://example.org/base/uri', 'http:this'], // @isaacs Disagree. Not how browsers do it. // @isaacs Disagree. Not how browsers do it.
['http:this', 'http://example.org/base/uri', "http://example.org/base/this"], // @isaacs Added // ['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'], ['http:this', 'http:base', 'http:this'],
['.//g', 'f:/a', 'f://g'], ['.//g', 'f:/a', 'f://g'],
['b/c//d/e', 'f://example.org/base/a', 'f://example.org/base/b/c//d/e'], ['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'], ['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'], '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'] ['../b/c', 'foo:a/y/z', 'foo:a/b/c']
].forEach(function (relativeTest) { ];
relativeTests2.forEach(function(relativeTest) {
var a = url.resolve(relativeTest[1], relativeTest[0]), var a = url.resolve(relativeTest[1], relativeTest[0]),
e = relativeTest[2]; e = relativeTest[2];
assert.equal(e, a, assert.equal(e, a,
"resolve("+[relativeTest[1], relativeTest[0]]+") == "+e+ 'resolve(' + [relativeTest[1], relativeTest[0]] + ') == ' + e +
"\n actual="+a); '\n actual=' + a);
}); });

Loading…
Cancel
Save