all da files

This commit is contained in:
jllord
2013-05-27 13:45:59 -07:00
commit 59d3d30afa
6704 changed files with 1954956 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@@ -0,0 +1,40 @@
var spawn = require('child_process').spawn
, exitCode = 0
, timeout = 10000
, fs = require('fs')
;
fs.readdir(__dirname, function (e, files) {
if (e) throw e
var tests = files.filter(function (f) {return f.slice(0, 'test-'.length) === 'test-'})
var next = function () {
if (tests.length === 0) process.exit(exitCode);
var file = tests.shift()
console.log(file)
var proc = spawn('node', [ 'tests/' + file ])
var killed = false
var t = setTimeout(function () {
proc.kill()
exitCode += 1
console.error(file + ' timeout')
killed = true
}, timeout)
proc.stdout.pipe(process.stdout)
proc.stderr.pipe(process.stderr)
proc.on('exit', function (code) {
if (code && !killed) console.error(file + ' failed')
exitCode += code || 0
clearTimeout(t)
next()
})
}
next()
})

View File

@@ -0,0 +1,90 @@
var fs = require('fs')
, http = require('http')
, path = require('path')
, https = require('https')
, events = require('events')
, stream = require('stream')
, assert = require('assert')
;
exports.createServer = function (port) {
port = port || 6767
var s = http.createServer(function (req, resp) {
s.emit(req.url, req, resp);
})
s.port = port
s.url = 'http://localhost:'+port
return s;
}
exports.createSSLServer = function(port, opts) {
port = port || 16767
var options = { 'key' : path.join(__dirname, 'ssl', 'test.key')
, 'cert': path.join(__dirname, 'ssl', 'test.crt')
}
if (opts) {
for (var i in opts) options[i] = opts[i]
}
for (var i in options) {
options[i] = fs.readFileSync(options[i])
}
var s = https.createServer(options, function (req, resp) {
s.emit(req.url, req, resp);
})
s.port = port
s.url = 'https://localhost:'+port
return s;
}
exports.createPostStream = function (text) {
var postStream = new stream.Stream();
postStream.writeable = true;
postStream.readable = true;
setTimeout(function () {postStream.emit('data', new Buffer(text)); postStream.emit('end')}, 0);
return postStream;
}
exports.createPostValidator = function (text, reqContentType) {
var l = function (req, resp) {
var r = '';
req.on('data', function (chunk) {r += chunk})
req.on('end', function () {
if (req.headers['content-type'] && req.headers['content-type'].indexOf('boundary=') >= 0) {
var boundary = req.headers['content-type'].split('boundary=')[1];
text = text.replace(/__BOUNDARY__/g, boundary);
}
if (r !== text) console.log(r, text);
assert.equal(r, text)
if (reqContentType) {
assert.ok(req.headers['content-type'])
assert.ok(~req.headers['content-type'].indexOf(reqContentType))
}
resp.writeHead(200, {'content-type':'text/plain'})
resp.write('OK')
resp.end()
})
}
return l;
}
exports.createGetResponse = function (text, contentType) {
var l = function (req, resp) {
contentType = contentType || 'text/plain'
resp.writeHead(200, {'content-type':contentType})
resp.write(text)
resp.end()
}
return l;
}
exports.createChunkResponse = function (chunks, contentType) {
var l = function (req, resp) {
contentType = contentType || 'text/plain'
resp.writeHead(200, {'content-type':contentType})
chunks.forEach(function (chunk) {
resp.write(chunk)
})
resp.end()
}
return l;
}

View File

@@ -0,0 +1,77 @@
#
# Recommended minimum configuration:
#
acl manager proto cache_object
acl localhost src 127.0.0.1/32 ::1
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1
# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8 # RFC1918 possible internal network
acl localnet src 172.16.0.0/12 # RFC1918 possible internal network
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network
acl localnet src fc00::/7 # RFC 4193 local private network range
acl localnet src fe80::/10 # RFC 4291 link-local (directly plugged) machines
acl SSL_ports port 443
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 # https
acl Safe_ports port 70 # gopher
acl Safe_ports port 210 # wais
acl Safe_ports port 1025-65535 # unregistered ports
acl Safe_ports port 280 # http-mgmt
acl Safe_ports port 488 # gss-http
acl Safe_ports port 591 # filemaker
acl Safe_ports port 777 # multiling http
acl CONNECT method CONNECT
#
# Recommended minimum Access Permission configuration:
#
# Only allow cachemgr access from localhost
http_access allow manager localhost
http_access deny manager
# Deny requests to certain unsafe ports
http_access deny !Safe_ports
# Deny CONNECT to other than secure SSL ports
#http_access deny CONNECT !SSL_ports
# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost
# And finally deny all other access to this proxy
http_access deny all
# Squid normally listens to port 3128
http_port 3128
# We recommend you to use at least the following line.
hierarchy_stoplist cgi-bin ?
# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /usr/local/var/cache 100 16 256
# Leave coredumps in the first cache dir
coredump_dir /usr/local/var/cache
# Add any of your own refresh_pattern entries above these.
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern -i (/cgi-bin/|\?) 0 0% 0
refresh_pattern . 0 20% 4320

View File

@@ -0,0 +1,20 @@
[ req ]
default_bits = 1024
days = 3650
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
output_password = password
[ req_distinguished_name ]
C = US
ST = CA
L = Oakland
O = request
OU = request Certificate Authority
CN = requestCA
emailAddress = mikeal@mikealrogers.com
[ req_attributes ]
challengePassword = password challenge

View File

View File

@@ -0,0 +1,17 @@
-----BEGIN CERTIFICATE-----
MIICvTCCAiYCCQDn+P/MSbDsWjANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMRAwDgYDVQQKEwdyZXF1
ZXN0MSYwJAYDVQQLEx1yZXF1ZXN0IENlcnRpZmljYXRlIEF1dGhvcml0eTESMBAG
A1UEAxMJcmVxdWVzdENBMSYwJAYJKoZIhvcNAQkBFhdtaWtlYWxAbWlrZWFscm9n
ZXJzLmNvbTAeFw0xMjAzMDEyMjUwNTZaFw0yMjAyMjcyMjUwNTZaMIGiMQswCQYD
VQQGEwJVUzELMAk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7Qh6RcALRCAZTWR5QtEf
dX+iSNJ4E85qXs0PqwkMDkoaxIJ+tmIRJY7y8oeylV8cfGAi8Soubt/i3SlR8IHC
uDMas/2OnwafK3N7ODeE1i7r7wkzQkSHaEz0TrF8XRnP25jAICCSLiMdAAjKfxVb
EvzsFSuAy3Jt6bU3hSLY9o4YVYKE+68ITMv9yNjvTsEiW+T+IbN34w==
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1 @@
ADF62016AA40C9C3

View File

@@ -0,0 +1,19 @@
[ req ]
default_bits = 1024
days = 3650
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
[ req_distinguished_name ]
C = US
ST = CA
L = Oakland
O = request
OU = testing
CN = testing.request.mikealrogers.com
emailAddress = mikeal@mikealrogers.com
[ req_attributes ]
challengePassword = password challenge

View File

@@ -0,0 +1,16 @@
-----BEGIN CERTIFICATE-----
MIICejCCAeMCCQCt9iAWqkDJwzANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMRAwDgYDVQQKEwdyZXF1
ZXN0MSYwJAYDVQQLEx1yZXF1ZXN0IENlcnRpZmljYXRlIEF1dGhvcml0eTESMBAG
A1UEAxMJcmVxdWVzdENBMSYwJAYJKoZIhvcNAQkBFhdtaWtlYWxAbWlrZWFscm9n
ZXJzLmNvbTAeFw0xMjAzMDEyMjUwNTZaFw0yMjAyMjcyMjUwNTZaMIGjMQswCQYD
VQQGEwJVUzELMAkGA1UECBMCQ0ExEDAOBgNVBAcTB09ha2xhbmQxEDAOBgNVBAoT
B3JlcXVlc3QxEDAOBgNVBAsTB3Rlc3RpbmcxKTAnBgNVBAMTIHRlc3RpbmcucmVx
dWVzdC5taWtlYWxyb2dlcnMuY29tMSYwJAYJKoZIhvcNAQkBFhdtaWtlYWxAbWlr
ZWFscm9nZXJzLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDgVl0jMumvOpmM
20W5v9yhGgZj8hPhEQF/N7yCBVBn/rWGYm70IHC8T/pR5c0LkWc5gdnCJEvKWQjh
DBKxZD8FAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEABShRkNgFbgs4vUWW9R9deNJj
7HJoiTmvkmoOC7QzcYkjdgHbOxsSq3rBnwxsVjY9PAtPwBn0GRspOeG7KzKRgySB
kb22LyrCFKbEOfKO/+CJc80ioK9zEPVjGsFMyAB+ftYRqM+s/4cQlTg/m89l01wC
yapjN3RxZbInGhWR+jA=
-----END CERTIFICATE-----

View File

@@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE REQUEST-----
MIIBgjCCASwCAQAwgaMxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEQMA4GA1UE
BxMHT2FrbGFuZDEQMA4GA1UEChMHcmVxdWVzdDEQMA4GA1UECxMHdGVzdGluZzEp
MCcGA1UEAxMgdGVzdGluZy5yZXF1ZXN0Lm1pa2VhbHJvZ2Vycy5jb20xJjAkBgkq
hkiG9w0BCQEWF21pa2VhbEBtaWtlYWxyb2dlcnMuY29tMFwwDQYJKoZIhvcNAQEB
BQADSwAwSAJBAOBWXSMy6a86mYzbRbm/3KEaBmPyE+ERAX83vIIFUGf+tYZibvQg
cLxP+lHlzQuRZzmB2cIkS8pZCOEMErFkPwUCAwEAAaAjMCEGCSqGSIb3DQEJBzEU
ExJwYXNzd29yZCBjaGFsbGVuZ2UwDQYJKoZIhvcNAQEFBQADQQBD3E5WekQzCEJw
7yOcqvtPYIxGaX8gRKkYfLPoj3pm3GF5SGqtJKhylKfi89szHXgktnQgzff9FN+A
HidVJ/3u
-----END CERTIFICATE REQUEST-----

View File

@@ -0,0 +1,28 @@
var fs = require("fs")
var https = require("https")
var options = { key: fs.readFileSync("./server.key")
, cert: fs.readFileSync("./server.crt") }
var server = https.createServer(options, function (req, res) {
res.writeHead(200)
res.end()
server.close()
})
server.listen(1337)
var ca = fs.readFileSync("./ca.crt")
var agent = new https.Agent({ host: "localhost", port: 1337, ca: ca })
https.request({ host: "localhost"
, method: "HEAD"
, port: 1337
, headers: { host: "testing.request.mikealrogers.com" }
, agent: agent
, ca: [ ca ]
, path: "/" }, function (res) {
if (res.client.authorized) {
console.log("node test: OK")
} else {
throw new Error(res.client.authorizationError)
}
}).end()

View File

@@ -0,0 +1,9 @@
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAOBWXSMy6a86mYzbRbm/3KEaBmPyE+ERAX83vIIFUGf+tYZibvQg
cLxP+lHlzQuRZzmB2cIkS8pZCOEMErFkPwUCAwEAAQJAK+r8ZM2sze8s7FRo/ApB
iRBtO9fCaIdJwbwJnXKo4RKwZDt1l2mm+fzZ+/QaQNjY1oTROkIIXmnwRvZWfYlW
gQIhAPKYsG+YSBN9o8Sdp1DMyZ/rUifKX3OE6q9tINkgajDVAiEA7Ltqh01+cnt0
JEnud/8HHcuehUBLMofeg0G+gCnSbXECIQCqDvkXsWNNLnS/3lgsnvH0Baz4sbeJ
rjIpuVEeg8eM5QIgbu0+9JmOV6ybdmmiMV4yAncoF35R/iKGVHDZCAsQzDECIQDZ
0jGz22tlo5YMcYSqrdD3U4sds1pwiAaWFRbCunoUJw==
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,16 @@
-----BEGIN CERTIFICATE-----
MIIChzCCAfACCQDauvz/KHp8ejANBgkqhkiG9w0BAQUFADCBhzELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMQwwCgYDVQQKEwNucG0x
IjAgBgNVBAsTGW5wbSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxDjAMBgNVBAMTBW5w
bUNBMRcwFQYJKoZIhvcNAQkBFghpQGl6cy5tZTAeFw0xMTA5MDUwMTQ3MTdaFw0y
MTA5MDIwMTQ3MTdaMIGHMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEDAOBgNV
BAcTB09ha2xhbmQxDDAKBgNVBAoTA25wbTEiMCAGA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fVZwB193YSivcgt778xlAkEAprYUz3jczjF5r2hrgbizPzPDR94tM5BTO3ki2v3w
kbf+j2g7FNAx6kZiVN8XwfLc8xEeUGiPKwtq3ddPDFh17w==
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,74 @@
var assert = require('assert')
, http = require('http')
, request = require('../index')
;
var numBasicRequests = 0;
var basicServer = http.createServer(function (req, res) {
console.error('Basic auth server: ', req.method, req.url);
numBasicRequests++;
var ok;
if (req.headers.authorization) {
if (req.headers.authorization == 'Basic ' + new Buffer('test:testing2').toString('base64')) {
ok = true;
} else {
// Bad auth header, don't send back WWW-Authenticate header
ok = false;
}
} else {
// No auth header, send back WWW-Authenticate header
ok = false;
res.setHeader('www-authenticate', 'Basic realm="Private"');
}
if (ok) {
console.log('request ok');
res.end('ok');
} else {
console.log('status=401');
res.statusCode = 401;
res.end('401');
}
});
basicServer.listen(6767);
request({
'method': 'GET',
'uri': 'http://localhost:6767/test/',
'auth': {
'user': 'test',
'pass': 'testing2',
'sendImmediately': false
}
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(numBasicRequests, 2);
// If we don't set sendImmediately = false, request will send basic auth
request({
'method': 'GET',
'uri': 'http://localhost:6767/test2/',
'auth': {
'user': 'test',
'pass': 'testing2'
}
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(numBasicRequests, 3);
request({
'method': 'GET',
'uri': 'http://test:testing2@localhost:6767/test2/'
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(numBasicRequests, 4);
console.log('All tests passed');
basicServer.close();
});
});
});

View File

@@ -0,0 +1,122 @@
var server = require('./server')
, events = require('events')
, stream = require('stream')
, assert = require('assert')
, request = require('../index')
;
var s = server.createServer();
var tests =
{ testGet :
{ resp : server.createGetResponse("TESTING!")
, expectBody: "TESTING!"
}
, testGetChunkBreak :
{ resp : server.createChunkResponse(
[ new Buffer([239])
, new Buffer([163])
, new Buffer([191])
, new Buffer([206])
, new Buffer([169])
, new Buffer([226])
, new Buffer([152])
, new Buffer([131])
])
, expectBody: "Ω☃"
}
, testGetBuffer :
{ resp : server.createGetResponse(new Buffer("TESTING!"))
, encoding: null
, expectBody: new Buffer("TESTING!")
}
, testGetEncoding :
{ resp : server.createGetResponse(new Buffer('efa3bfcea9e29883', 'hex'))
, encoding: 'hex'
, expectBody: "efa3bfcea9e29883"
}
, testGetUTF8:
{ resp: server.createGetResponse(new Buffer([0xEF, 0xBB, 0xBF, 226, 152, 131]))
, encoding: "utf8"
, expectBody: "☃"
}
, testGetJSON :
{ resp : server.createGetResponse('{"test":true}', 'application/json')
, json : true
, expectBody: {"test":true}
}
, testPutString :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : "PUTTINGDATA"
}
, testPutBuffer :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : new Buffer("PUTTINGDATA")
}
, testPutJSON :
{ resp : server.createPostValidator(JSON.stringify({foo: 'bar'}))
, method: "PUT"
, json: {foo: 'bar'}
}
, testPutMultipart :
{ resp: server.createPostValidator(
'--__BOUNDARY__\r\n' +
'content-type: text/html\r\n' +
'\r\n' +
'<html><body>Oh hi.</body></html>' +
'\r\n--__BOUNDARY__\r\n\r\n' +
'Oh hi.' +
'\r\n--__BOUNDARY__--'
)
, method: "PUT"
, multipart:
[ {'content-type': 'text/html', 'body': '<html><body>Oh hi.</body></html>'}
, {'body': 'Oh hi.'}
]
}
, testPutMultipartPreambleCRLF :
{ resp: server.createPostValidator(
'\r\n--__BOUNDARY__\r\n' +
'content-type: text/html\r\n' +
'\r\n' +
'<html><body>Oh hi.</body></html>' +
'\r\n--__BOUNDARY__\r\n\r\n' +
'Oh hi.' +
'\r\n--__BOUNDARY__--'
)
, method: "PUT"
, preambleCRLF: true
, multipart:
[ {'content-type': 'text/html', 'body': '<html><body>Oh hi.</body></html>'}
, {'body': 'Oh hi.'}
]
}
}
s.listen(s.port, function () {
var counter = 0
for (i in tests) {
(function () {
var test = tests[i]
s.on('/'+i, test.resp)
test.uri = s.url + '/' + i
request(test, function (err, resp, body) {
if (err) throw err
if (test.expectBody) {
assert.deepEqual(test.expectBody, body)
}
counter = counter - 1;
if (counter === 0) {
console.log(Object.keys(tests).length+" tests passed.")
s.close()
}
})
counter++
})()
}
})

View File

@@ -0,0 +1,129 @@
var server = require('./server')
, assert = require('assert')
, request = require('../index')
;
var s = server.createServer();
s.listen(s.port, function () {
var counter = 0;
s.on('/get', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.method, 'GET')
resp.writeHead(200, {'Content-Type': 'text/plain'});
resp.end('TESTING!');
});
// test get(string, function)
request.defaults({headers:{foo:"bar"}})(s.url + '/get', function (e, r, b){
if (e) throw e;
assert.deepEqual("TESTING!", b);
counter += 1;
});
s.on('/post', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.headers['content-type'], null);
assert.equal(req.method, 'POST')
resp.writeHead(200, {'Content-Type': 'application/json'});
resp.end(JSON.stringify({foo:'bar'}));
});
// test post(string, object, function)
request.defaults({headers:{foo:"bar"}}).post(s.url + '/post', {json: true}, function (e, r, b){
if (e) throw e;
assert.deepEqual('bar', b.foo);
counter += 1;
});
s.on('/patch', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.headers['content-type'], null);
assert.equal(req.method, 'PATCH')
resp.writeHead(200, {'Content-Type': 'application/json'});
resp.end(JSON.stringify({foo:'bar'}));
});
// test post(string, object, function)
request.defaults({headers:{foo:"bar"}}).patch(s.url + '/patch', {json: true}, function (e, r, b){
if (e) throw e;
assert.deepEqual('bar', b.foo);
counter += 1;
});
s.on('/post-body', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.headers['content-type'], 'application/json');
assert.equal(req.method, 'POST')
resp.writeHead(200, {'Content-Type': 'application/json'});
resp.end(JSON.stringify({foo:'bar'}));
});
// test post(string, object, function) with body
request.defaults({headers:{foo:"bar"}}).post(s.url + '/post-body', {json: true, body:{bar:"baz"}}, function (e, r, b){
if (e) throw e;
assert.deepEqual('bar', b.foo);
counter += 1;
});
s.on('/del', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.method, 'DELETE')
resp.writeHead(200, {'Content-Type': 'application/json'});
resp.end(JSON.stringify({foo:'bar'}));
});
// test .del(string, function)
request.defaults({headers:{foo:"bar"}, json:true}).del(s.url + '/del', function (e, r, b){
if (e) throw e;
assert.deepEqual('bar', b.foo);
counter += 1;
});
s.on('/head', function (req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.method, 'HEAD')
resp.writeHead(200, {'Content-Type': 'text/plain'});
resp.end();
});
// test head.(object, function)
request.defaults({headers:{foo:"bar"}}).head({uri: s.url + '/head'}, function (e, r, b){
if (e) throw e;
counter += 1;
});
s.on('/get_custom', function(req, resp) {
assert.equal(req.headers.foo, 'bar');
assert.equal(req.headers.x, 'y');
resp.writeHead(200, {'Content-Type': 'text/plain'});
resp.end();
});
// test custom request handler function
var defaultRequest = request.defaults({
headers:{foo:"bar"}
, body: 'TESTING!'
}, function(uri, options, callback) {
var params = request.initParams(uri, options, callback);
options = params.options;
options.headers.x = 'y';
return request(params.uri, params.options, params.callback);
});
var msg = 'defaults test failed. head request should throw earlier';
assert.throws(function() {
defaultRequest.head(s.url + '/get_custom', function(e, r, b) {
throw new Error(msg);
});
counter+=1;
}, msg);
defaultRequest.get(s.url + '/get_custom', function(e, r, b) {
if(e) throw e;
counter += 1;
console.log(counter.toString() + " tests passed.");
s.close();
});
})

View File

@@ -0,0 +1,69 @@
var assert = require('assert')
, http = require('http')
, request = require('../index')
;
// Test digest auth
// Using header values captured from interaction with Apache
var numDigestRequests = 0;
var digestServer = http.createServer(function (req, res) {
console.error('Digest auth server: ', req.method, req.url);
numDigestRequests++;
var ok;
if (req.headers.authorization) {
if (req.headers.authorization == 'Digest username="test", realm="Private", nonce="WpcHS2/TBAA=dffcc0dbd5f96d49a5477166649b7c0ae3866a93", uri="/test/", qop="auth", response="54753ce37c10cb20b09b769f0bed730e", nc="1", cnonce=""') {
ok = true;
} else {
// Bad auth header, don't send back WWW-Authenticate header
ok = false;
}
} else {
// No auth header, send back WWW-Authenticate header
ok = false;
res.setHeader('www-authenticate', 'Digest realm="Private", nonce="WpcHS2/TBAA=dffcc0dbd5f96d49a5477166649b7c0ae3866a93", algorithm=MD5, qop="auth"');
}
if (ok) {
console.log('request ok');
res.end('ok');
} else {
console.log('status=401');
res.statusCode = 401;
res.end('401');
}
});
digestServer.listen(6767);
request({
'method': 'GET',
'uri': 'http://localhost:6767/test/',
'auth': {
'user': 'test',
'pass': 'testing',
'sendImmediately': false
}
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(numDigestRequests, 2);
// If we don't set sendImmediately = false, request will send basic auth
request({
'method': 'GET',
'uri': 'http://localhost:6767/test/',
'auth': {
'user': 'test',
'pass': 'testing'
}
}, function(error, response, body) {
assert.equal(response.statusCode, 401);
assert.equal(numDigestRequests, 3);
console.log('All tests passed');
digestServer.close();
});
});

View File

@@ -0,0 +1,37 @@
var server = require('./server')
, events = require('events')
, assert = require('assert')
, request = require('../index')
;
var local = 'http://localhost:8888/asdf'
try {
request({uri:local, body:{}})
assert.fail("Should have throw")
} catch(e) {
assert.equal(e.message, 'Argument error, options.body.')
}
try {
request({uri:local, multipart: 'foo'})
assert.fail("Should have throw")
} catch(e) {
assert.equal(e.message, 'Argument error, options.multipart.')
}
try {
request({uri:local, multipart: [{}]})
assert.fail("Should have throw")
} catch(e) {
assert.equal(e.message, 'Body attribute missing in multipart.')
}
try {
request(local, {multipart: [{}]})
assert.fail("Should have throw")
} catch(e) {
assert.equal(e.message, 'Body attribute missing in multipart.')
}
console.log("All tests passed.")

View File

@@ -0,0 +1,30 @@
var request = require('../index');
var http = require('http');
var requests = 0;
var assert = require('assert');
var server = http.createServer(function (req, res) {
console.error(req.method, req.url);
requests ++;
if (req.method === 'POST') {
console.error('send 303');
res.setHeader('location', req.url);
res.statusCode = 303;
res.end('try again, i guess\n');
} else {
console.error('send 200')
res.end('ok: ' + requests);
}
});
server.listen(6767);
request.post({ url: 'http://localhost:6767/foo',
followAllRedirects: true,
form: { foo: 'bar' } }, function (er, req, body) {
if (er) throw er;
assert.equal(body, 'ok: 2');
assert.equal(requests, 2);
console.error('ok - ' + process.version);
server.close();
});

View File

@@ -0,0 +1,35 @@
var request = require('../index');
var http = require('http');
var requests = 0;
var assert = require('assert');
var server = http.createServer(function (req, res) {
requests ++;
// redirect everything 3 times, no matter what.
var c = req.headers.cookie;
if (!c) c = 0;
else c = +c.split('=')[1] || 0;
if (c > 3) {
res.end('ok: '+requests);
return;
}
res.setHeader('set-cookie', 'c=' + (c + 1));
res.setHeader('location', req.url);
res.statusCode = 302;
res.end('try again, i guess\n');
});
server.listen(6767);
request.post({ url: 'http://localhost:6767/foo',
followAllRedirects: true,
form: { foo: 'bar' } }, function (er, req, body) {
if (er) throw er;
assert.equal(body, 'ok: 5');
assert.equal(requests, 5);
console.error('ok - ' + process.version);
server.close();
});

View File

@@ -0,0 +1,79 @@
var assert = require('assert')
var http = require('http');
var path = require('path');
var mime = require('mime');
var request = require('../index');
var fs = require('fs');
var remoteFile = 'http://nodejs.org/images/logo.png';
var FIELDS = [
{name: 'my_field', value: 'my_value'},
{name: 'my_buffer', value: new Buffer([1, 2, 3])},
{name: 'my_file', value: fs.createReadStream(__dirname + '/unicycle.jpg')},
{name: 'remote_file', value: request(remoteFile) }
];
var server = http.createServer(function(req, res) {
// temp workaround
var data = '';
req.setEncoding('utf8');
req.on('data', function(d) {
data += d;
});
req.on('end', function() {
// check for the fields' traces
// 1st field : my_field
var field = FIELDS.shift();
assert.ok( data.indexOf('form-data; name="'+field.name+'"') != -1 );
assert.ok( data.indexOf(field.value) != -1 );
// 2nd field : my_buffer
var field = FIELDS.shift();
assert.ok( data.indexOf('form-data; name="'+field.name+'"') != -1 );
assert.ok( data.indexOf(field.value) != -1 );
// 3rd field : my_file
var field = FIELDS.shift();
assert.ok( data.indexOf('form-data; name="'+field.name+'"') != -1 );
assert.ok( data.indexOf('; filename="'+path.basename(field.value.path)+'"') != -1 );
// check for unicycle.jpg traces
assert.ok( data.indexOf('2005:06:21 01:44:12') != -1 );
assert.ok( data.indexOf('Content-Type: '+mime.lookup(field.value.path) ) != -1 );
// 4th field : remote_file
var field = FIELDS.shift();
assert.ok( data.indexOf('form-data; name="'+field.name+'"') != -1 );
assert.ok( data.indexOf('; filename="'+path.basename(field.value.path)+'"') != -1 );
// check for http://nodejs.org/images/logo.png traces
assert.ok( data.indexOf('ImageReady') != -1 );
assert.ok( data.indexOf('Content-Type: '+mime.lookup(remoteFile) ) != -1 );
res.writeHead(200);
res.end('done');
});
});
server.listen(8080, function() {
var req = request.post('http://localhost:8080/upload', function () {
server.close();
})
var form = req.form()
FIELDS.forEach(function(field) {
form.append(field.name, field.value);
});
});
process.on('exit', function() {
assert.strictEqual(FIELDS.length, 0);
});

View File

@@ -0,0 +1,33 @@
var createServer = require('http').createServer
, request = require('../index')
, hawk = require('hawk')
, assert = require('assert')
;
var server = createServer(function (req, resp) {
var getCred = function (id, callback) {
assert.equal(id, 'dh37fgj492je')
var credentials =
{ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn'
, algorithm: 'sha256'
, user: 'Steve'
}
return callback(null, credentials)
}
hawk.server.authenticate(req, getCred, {}, function (err, credentials, attributes) {
resp.writeHead(!err ? 200 : 401, { 'Content-Type': 'text/plain' })
resp.end(!err ? 'Hello ' + credentials.user : 'Shoosh!')
})
})
server.listen(8080, function () {
var creds = {key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: 'sha256', id:'dh37fgj492je'}
request('http://localhost:8080', {hawk:{credentials:creds}}, function (e, r, b) {
assert.equal(200, r.statusCode)
assert.equal(b, 'Hello Steve')
server.close()
})
})

View File

@@ -0,0 +1,52 @@
var server = require('./server')
, assert = require('assert')
, request = require('../index')
, Cookie = require('cookie-jar')
, Jar = Cookie.Jar
, s = server.createServer()
s.listen(s.port, function () {
var serverUri = 'http://localhost:' + s.port
, numTests = 0
, numOutstandingTests = 0
function createTest(requestObj, serverAssertFn) {
var testNumber = numTests;
numTests += 1;
numOutstandingTests += 1;
s.on('/' + testNumber, function (req, res) {
serverAssertFn(req, res);
res.writeHead(200);
res.end();
});
requestObj.url = serverUri + '/' + testNumber
request(requestObj, function (err, res, body) {
assert.ok(!err)
assert.equal(res.statusCode, 200)
numOutstandingTests -= 1
if (numOutstandingTests === 0) {
console.log(numTests + ' tests passed.')
s.close()
}
})
}
// Issue #125: headers.cookie shouldn't be replaced when a cookie jar isn't specified
createTest({headers: {cookie: 'foo=bar'}}, function (req, res) {
assert.ok(req.headers.cookie)
assert.equal(req.headers.cookie, 'foo=bar')
})
// Issue #125: headers.cookie + cookie jar
var jar = new Jar()
jar.add(new Cookie('quux=baz'));
createTest({jar: jar, headers: {cookie: 'foo=bar'}}, function (req, res) {
assert.ok(req.headers.cookie)
assert.equal(req.headers.cookie, 'foo=bar; quux=baz')
})
// There should be no cookie header when neither headers.cookie nor a cookie jar is specified
createTest({}, function (req, res) {
assert.ok(!req.headers.cookie)
})
})

View File

@@ -0,0 +1,94 @@
var http = require('http')
, https = require('https')
, server = require('./server')
, assert = require('assert')
, request = require('../index')
var faux_requests_made = {'http':0, 'https':0}
function wrap_request(name, module) {
// Just like the http or https module, but note when a request is made.
var wrapped = {}
Object.keys(module).forEach(function(key) {
var value = module[key];
if(key != 'request')
wrapped[key] = value;
else
wrapped[key] = function(options, callback) {
faux_requests_made[name] += 1
return value.apply(this, arguments)
}
})
return wrapped;
}
var faux_http = wrap_request('http', http)
, faux_https = wrap_request('https', https)
, plain_server = server.createServer()
, https_server = server.createSSLServer()
plain_server.listen(plain_server.port, function() {
plain_server.on('/plain', function (req, res) {
res.writeHead(200)
res.end('plain')
})
plain_server.on('/to_https', function (req, res) {
res.writeHead(301, {'location':'https://localhost:'+https_server.port + '/https'})
res.end()
})
https_server.listen(https_server.port, function() {
https_server.on('/https', function (req, res) {
res.writeHead(200)
res.end('https')
})
https_server.on('/to_plain', function (req, res) {
res.writeHead(302, {'location':'http://localhost:'+plain_server.port + '/plain'})
res.end()
})
run_tests()
run_tests({})
run_tests({'http:':faux_http})
run_tests({'https:':faux_https})
run_tests({'http:':faux_http, 'https:':faux_https})
})
})
function run_tests(httpModules) {
var to_https = 'http://localhost:'+plain_server.port+'/to_https'
var to_plain = 'https://localhost:'+https_server.port+'/to_plain'
request(to_https, {'httpModules':httpModules, strictSSL:false}, function (er, res, body) {
if (er) throw er
assert.equal(body, 'https', 'Received HTTPS server body')
done()
})
request(to_plain, {'httpModules':httpModules, strictSSL:false}, function (er, res, body) {
if (er) throw er
assert.equal(body, 'plain', 'Received HTTPS server body')
done()
})
}
var passed = 0;
function done() {
passed += 1
var expected = 10
if(passed == expected) {
plain_server.close()
https_server.close()
assert.equal(faux_requests_made.http, 4, 'Wrapped http module called appropriately')
assert.equal(faux_requests_made.https, 4, 'Wrapped https module called appropriately')
console.log((expected+2) + ' tests passed.')
}
}

View File

@@ -0,0 +1,97 @@
// a test where we validate the siguature of the keys
// otherwise exactly the same as the ssl test
var server = require('./server')
, assert = require('assert')
, request = require('../index')
, fs = require('fs')
, path = require('path')
, opts = { key: path.resolve(__dirname, 'ssl/ca/server.key')
, cert: path.resolve(__dirname, 'ssl/ca/server.crt') }
, s = server.createSSLServer(null, opts)
, caFile = path.resolve(__dirname, 'ssl/ca/ca.crt')
, ca = fs.readFileSync(caFile)
var tests =
{ testGet :
{ resp : server.createGetResponse("TESTING!")
, expectBody: "TESTING!"
}
, testGetChunkBreak :
{ resp : server.createChunkResponse(
[ new Buffer([239])
, new Buffer([163])
, new Buffer([191])
, new Buffer([206])
, new Buffer([169])
, new Buffer([226])
, new Buffer([152])
, new Buffer([131])
])
, expectBody: "Ω☃"
}
, testGetJSON :
{ resp : server.createGetResponse('{"test":true}', 'application/json')
, json : true
, expectBody: {"test":true}
}
, testPutString :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : "PUTTINGDATA"
}
, testPutBuffer :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : new Buffer("PUTTINGDATA")
}
, testPutJSON :
{ resp : server.createPostValidator(JSON.stringify({foo: 'bar'}))
, method: "PUT"
, json: {foo: 'bar'}
}
, testPutMultipart :
{ resp: server.createPostValidator(
'--__BOUNDARY__\r\n' +
'content-type: text/html\r\n' +
'\r\n' +
'<html><body>Oh hi.</body></html>' +
'\r\n--__BOUNDARY__\r\n\r\n' +
'Oh hi.' +
'\r\n--__BOUNDARY__--'
)
, method: "PUT"
, multipart:
[ {'content-type': 'text/html', 'body': '<html><body>Oh hi.</body></html>'}
, {'body': 'Oh hi.'}
]
}
}
s.listen(s.port, function () {
var counter = 0
for (i in tests) {
(function () {
var test = tests[i]
s.on('/'+i, test.resp)
test.uri = s.url + '/' + i
test.strictSSL = true
test.ca = ca
test.headers = { host: 'testing.request.mikealrogers.com' }
request(test, function (err, resp, body) {
if (err) throw err
if (test.expectBody) {
assert.deepEqual(test.expectBody, body)
}
counter = counter - 1;
if (counter === 0) {
console.log(Object.keys(tests).length+" tests passed.")
s.close()
}
})
counter++
})()
}
})

View File

@@ -0,0 +1,87 @@
var server = require('./server')
, assert = require('assert')
, request = require('../index')
var s = server.createSSLServer();
var tests =
{ testGet :
{ resp : server.createGetResponse("TESTING!")
, expectBody: "TESTING!"
}
, testGetChunkBreak :
{ resp : server.createChunkResponse(
[ new Buffer([239])
, new Buffer([163])
, new Buffer([191])
, new Buffer([206])
, new Buffer([169])
, new Buffer([226])
, new Buffer([152])
, new Buffer([131])
])
, expectBody: "Ω☃"
}
, testGetJSON :
{ resp : server.createGetResponse('{"test":true}', 'application/json')
, json : true
, expectBody: {"test":true}
}
, testPutString :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : "PUTTINGDATA"
}
, testPutBuffer :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : new Buffer("PUTTINGDATA")
}
, testPutJSON :
{ resp : server.createPostValidator(JSON.stringify({foo: 'bar'}))
, method: "PUT"
, json: {foo: 'bar'}
}
, testPutMultipart :
{ resp: server.createPostValidator(
'--__BOUNDARY__\r\n' +
'content-type: text/html\r\n' +
'\r\n' +
'<html><body>Oh hi.</body></html>' +
'\r\n--__BOUNDARY__\r\n\r\n' +
'Oh hi.' +
'\r\n--__BOUNDARY__--'
)
, method: "PUT"
, multipart:
[ {'content-type': 'text/html', 'body': '<html><body>Oh hi.</body></html>'}
, {'body': 'Oh hi.'}
]
}
}
s.listen(s.port, function () {
var counter = 0
for (i in tests) {
(function () {
var test = tests[i]
s.on('/'+i, test.resp)
test.uri = s.url + '/' + i
test.rejectUnauthorized = false
request(test, function (err, resp, body) {
if (err) throw err
if (test.expectBody) {
assert.deepEqual(test.expectBody, body)
}
counter = counter - 1;
if (counter === 0) {
console.log(Object.keys(tests).length+" tests passed.")
s.close()
}
})
counter++
})()
}
})

View File

@@ -0,0 +1,117 @@
var hmacsign = require('oauth-sign').hmacsign
, assert = require('assert')
, qs = require('querystring')
, request = require('../index')
;
function getsignature (r) {
var sign
r.headers.Authorization.slice('OAuth '.length).replace(/,\ /g, ',').split(',').forEach(function (v) {
if (v.slice(0, 'oauth_signature="'.length) === 'oauth_signature="') sign = v.slice('oauth_signature="'.length, -1)
})
return decodeURIComponent(sign)
}
// Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth
var reqsign = hmacsign('POST', 'https://api.twitter.com/oauth/request_token',
{ oauth_callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11'
, oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g'
, oauth_nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk'
, oauth_signature_method: 'HMAC-SHA1'
, oauth_timestamp: '1272323042'
, oauth_version: '1.0'
}, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98")
console.log(reqsign)
console.log('8wUi7m5HFQy76nowoCThusfgB+Q=')
assert.equal(reqsign, '8wUi7m5HFQy76nowoCThusfgB+Q=')
var accsign = hmacsign('POST', 'https://api.twitter.com/oauth/access_token',
{ oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g'
, oauth_nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8'
, oauth_signature_method: 'HMAC-SHA1'
, oauth_token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc'
, oauth_timestamp: '1272323047'
, oauth_verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY'
, oauth_version: '1.0'
}, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA")
console.log(accsign)
console.log('PUw/dHA4fnlJYM6RhXk5IU/0fCc=')
assert.equal(accsign, 'PUw/dHA4fnlJYM6RhXk5IU/0fCc=')
var upsign = hmacsign('POST', 'http://api.twitter.com/1/statuses/update.json',
{ oauth_consumer_key: "GDdmIQH6jhtmLUypg82g"
, oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y"
, oauth_signature_method: "HMAC-SHA1"
, oauth_token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw"
, oauth_timestamp: "1272325550"
, oauth_version: "1.0"
, status: 'setting up my twitter 私のさえずりを設定する'
}, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA")
console.log(upsign)
console.log('yOahq5m0YjDDjfjxHaXEsW9D+X0=')
assert.equal(upsign, 'yOahq5m0YjDDjfjxHaXEsW9D+X0=')
var rsign = request.post(
{ url: 'https://api.twitter.com/oauth/request_token'
, oauth:
{ callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11'
, consumer_key: 'GDdmIQH6jhtmLUypg82g'
, nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk'
, timestamp: '1272323042'
, version: '1.0'
, consumer_secret: "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98"
}
})
setTimeout(function () {
console.log(getsignature(rsign))
assert.equal(reqsign, getsignature(rsign))
})
var raccsign = request.post(
{ url: 'https://api.twitter.com/oauth/access_token'
, oauth:
{ consumer_key: 'GDdmIQH6jhtmLUypg82g'
, nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8'
, signature_method: 'HMAC-SHA1'
, token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc'
, timestamp: '1272323047'
, verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY'
, version: '1.0'
, consumer_secret: "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98"
, token_secret: "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA"
}
})
setTimeout(function () {
console.log(getsignature(raccsign))
assert.equal(accsign, getsignature(raccsign))
}, 1)
var rupsign = request.post(
{ url: 'http://api.twitter.com/1/statuses/update.json'
, oauth:
{ consumer_key: "GDdmIQH6jhtmLUypg82g"
, nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y"
, signature_method: "HMAC-SHA1"
, token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw"
, timestamp: "1272325550"
, version: "1.0"
, consumer_secret: "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98"
, token_secret: "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA"
}
, form: {status: 'setting up my twitter 私のさえずりを設定する'}
})
setTimeout(function () {
console.log(getsignature(rupsign))
assert.equal(upsign, getsignature(rupsign))
}, 1)

View File

@@ -0,0 +1,93 @@
var server = require('./server')
, assert = require('assert')
, request = require('../index')
;
var s = server.createServer();
var tests =
{ testGet :
{ resp : server.createGetResponse("TESTING!")
, expectBody: "TESTING!"
}
, testGetChunkBreak :
{ resp : server.createChunkResponse(
[ new Buffer([239])
, new Buffer([163])
, new Buffer([191])
, new Buffer([206])
, new Buffer([169])
, new Buffer([226])
, new Buffer([152])
, new Buffer([131])
])
, expectBody: "Ω☃"
}
, testGetBuffer :
{ resp : server.createGetResponse(new Buffer("TESTING!"))
, encoding: null
, expectBody: new Buffer("TESTING!")
}
, testGetJSON :
{ resp : server.createGetResponse('{"test":true}', 'application/json')
, json : true
, expectBody: {"test":true}
}
, testPutString :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : "PUTTINGDATA"
}
, testPutBuffer :
{ resp : server.createPostValidator("PUTTINGDATA")
, method : "PUT"
, body : new Buffer("PUTTINGDATA")
}
, testPutJSON :
{ resp : server.createPostValidator(JSON.stringify({foo: 'bar'}))
, method: "PUT"
, json: {foo: 'bar'}
}
, testPutMultipart :
{ resp: server.createPostValidator(
'--__BOUNDARY__\r\n' +
'content-type: text/html\r\n' +
'\r\n' +
'<html><body>Oh hi.</body></html>' +
'\r\n--__BOUNDARY__\r\n\r\n' +
'Oh hi.' +
'\r\n--__BOUNDARY__--'
)
, method: "PUT"
, multipart:
[ {'content-type': 'text/html', 'body': '<html><body>Oh hi.</body></html>'}
, {'body': 'Oh hi.'}
]
}
}
s.listen(s.port, function () {
var counter = 0
for (i in tests) {
(function () {
var test = tests[i]
s.on('/'+i, test.resp)
//test.uri = s.url + '/' + i
request(s.url + '/' + i, test, function (err, resp, body) {
if (err) throw err
if (test.expectBody) {
assert.deepEqual(test.expectBody, body)
}
counter = counter - 1;
if (counter === 0) {
assert.notEqual(typeof test.callback, 'function')
console.log(1 + Object.keys(tests).length+" tests passed.")
s.close()
}
})
counter++
})()
}
})

View File

@@ -0,0 +1,42 @@
var http = require('http')
, assert = require('assert')
, request = require('../index')
;
var portOne = 8968
, portTwo = 8969
;
// server one
var s1 = http.createServer(function (req, resp) {
if (req.url == '/original') {
resp.writeHeader(302, {'location': '/redirected'})
resp.end()
} else if (req.url == '/redirected') {
resp.writeHeader(200, {'content-type': 'text/plain'})
resp.write('OK')
resp.end()
}
}).listen(portOne);
// server two
var s2 = http.createServer(function (req, resp) {
var x = request('http://localhost:'+portOne+'/original')
req.pipe(x)
x.pipe(resp)
}).listen(portTwo, function () {
var r = request('http://localhost:'+portTwo+'/original', function (err, res, body) {
assert.equal(body, 'OK')
s1.close()
s2.close()
});
// it hangs, so wait a second :)
r.timeout = 1000;
})

View File

@@ -0,0 +1,216 @@
var server = require('./server')
, events = require('events')
, stream = require('stream')
, assert = require('assert')
, fs = require('fs')
, request = require('../index')
, path = require('path')
, util = require('util')
;
var s = server.createServer(3453);
function ValidationStream(str) {
this.str = str
this.buf = ''
this.on('data', function (data) {
this.buf += data
})
this.on('end', function () {
assert.equal(this.str, this.buf)
})
this.writable = true
}
util.inherits(ValidationStream, stream.Stream)
ValidationStream.prototype.write = function (chunk) {
this.emit('data', chunk)
}
ValidationStream.prototype.end = function (chunk) {
if (chunk) emit('data', chunk)
this.emit('end')
}
s.listen(s.port, function () {
counter = 0;
var check = function () {
counter = counter - 1
if (counter === 0) {
console.log('All tests passed.')
setTimeout(function () {
process.exit();
}, 500)
}
}
// Test pipeing to a request object
s.once('/push', server.createPostValidator("mydata"));
var mydata = new stream.Stream();
mydata.readable = true
counter++
var r1 = request.put({url:'http://localhost:3453/push'}, function () {
check();
})
mydata.pipe(r1)
mydata.emit('data', 'mydata');
mydata.emit('end');
// Test pipeing to a request object with a json body
s.once('/push-json', server.createPostValidator("{\"foo\":\"bar\"}", "application/json"));
var mybodydata = new stream.Stream();
mybodydata.readable = true
counter++
var r2 = request.put({url:'http://localhost:3453/push-json',json:true}, function () {
check();
})
mybodydata.pipe(r2)
mybodydata.emit('data', JSON.stringify({foo:"bar"}));
mybodydata.emit('end');
// Test pipeing from a request object.
s.once('/pull', server.createGetResponse("mypulldata"));
var mypulldata = new stream.Stream();
mypulldata.writable = true
counter++
request({url:'http://localhost:3453/pull'}).pipe(mypulldata)
var d = '';
mypulldata.write = function (chunk) {
d += chunk;
}
mypulldata.end = function () {
assert.equal(d, 'mypulldata');
check();
};
s.on('/cat', function (req, resp) {
if (req.method === "GET") {
resp.writeHead(200, {'content-type':'text/plain-test', 'content-length':4});
resp.end('asdf')
} else if (req.method === "PUT") {
assert.equal(req.headers['content-type'], 'text/plain-test');
assert.equal(req.headers['content-length'], 4)
var validate = '';
req.on('data', function (chunk) {validate += chunk})
req.on('end', function () {
resp.writeHead(201);
resp.end();
assert.equal(validate, 'asdf');
check();
})
}
})
s.on('/pushjs', function (req, resp) {
if (req.method === "PUT") {
assert.equal(req.headers['content-type'], 'application/javascript');
check();
}
})
s.on('/catresp', function (req, resp) {
request.get('http://localhost:3453/cat').pipe(resp)
})
s.on('/doodle', function (req, resp) {
if (req.headers['x-oneline-proxy']) {
resp.setHeader('x-oneline-proxy', 'yup')
}
resp.writeHead('200', {'content-type':'image/jpeg'})
fs.createReadStream(path.join(__dirname, 'googledoodle.jpg')).pipe(resp)
})
s.on('/onelineproxy', function (req, resp) {
var x = request('http://localhost:3453/doodle')
req.pipe(x)
x.pipe(resp)
})
counter++
fs.createReadStream(__filename).pipe(request.put('http://localhost:3453/pushjs'))
counter++
request.get('http://localhost:3453/cat').pipe(request.put('http://localhost:3453/cat'))
counter++
request.get('http://localhost:3453/catresp', function (e, resp, body) {
assert.equal(resp.headers['content-type'], 'text/plain-test');
assert.equal(resp.headers['content-length'], 4)
check();
})
var doodleWrite = fs.createWriteStream(path.join(__dirname, 'test.jpg'))
counter++
request.get('http://localhost:3453/doodle').pipe(doodleWrite)
doodleWrite.on('close', function () {
assert.deepEqual(fs.readFileSync(path.join(__dirname, 'googledoodle.jpg')), fs.readFileSync(path.join(__dirname, 'test.jpg')))
check()
})
process.on('exit', function () {
fs.unlinkSync(path.join(__dirname, 'test.jpg'))
})
counter++
request.get({uri:'http://localhost:3453/onelineproxy', headers:{'x-oneline-proxy':'nope'}}, function (err, resp, body) {
assert.equal(resp.headers['x-oneline-proxy'], 'yup')
check()
})
s.on('/afterresponse', function (req, resp) {
resp.write('d')
resp.end()
})
counter++
var afterresp = request.post('http://localhost:3453/afterresponse').on('response', function () {
var v = new ValidationStream('d')
afterresp.pipe(v)
v.on('end', check)
})
s.on('/forward1', function (req, resp) {
resp.writeHead(302, {location:'/forward2'})
resp.end()
})
s.on('/forward2', function (req, resp) {
resp.writeHead('200', {'content-type':'image/png'})
resp.write('d')
resp.end()
})
counter++
var validateForward = new ValidationStream('d')
validateForward.on('end', check)
request.get('http://localhost:3453/forward1').pipe(validateForward)
// Test pipe options
s.once('/opts', server.createGetResponse('opts response'));
var optsStream = new stream.Stream();
optsStream.writable = true
var optsData = '';
optsStream.write = function (buf) {
optsData += buf;
if (optsData === 'opts response') {
setTimeout(check, 10);
}
}
optsStream.end = function () {
assert.fail('end called')
};
counter++
request({url:'http://localhost:3453/opts'}).pipe(optsStream, { end : false })
})

View File

@@ -0,0 +1,16 @@
var request = require('../index')
, http = require('http')
, assert = require('assert')
;
var s = http.createServer(function (req, resp) {
resp.statusCode = 200;
resp.end('asdf');
}).listen(8080, function () {
request({'url': 'http://localhost:8080', 'pool': false}, function (e, resp) {
var agent = resp.request.agent;
assert.strictEqual(typeof agent, 'boolean');
assert.strictEqual(agent, false);
s.close();
});
});

View File

@@ -0,0 +1,61 @@
var server = require('./server')
, assert = require('assert')
, request = require('../index')
var s = server.createServer()
var ss = server.createSSLServer()
var sUrl = 'http://localhost:' + s.port
var ssUrl = 'https://localhost:' + ss.port
s.listen(s.port, bouncy(s, ssUrl))
ss.listen(ss.port, bouncy(ss, sUrl))
var hits = {}
var expect = {}
var pending = 0
function bouncy (s, server) { return function () {
var redirs = { a: 'b'
, b: 'c'
, c: 'd'
, d: 'e'
, e: 'f'
, f: 'g'
, g: 'h'
, h: 'end' }
var perm = true
Object.keys(redirs).forEach(function (p) {
var t = redirs[p]
// switch type each time
var type = perm ? 301 : 302
perm = !perm
s.on('/' + p, function (req, res) {
res.writeHead(type, { location: server + '/' + t })
res.end()
})
})
s.on('/end', function (req, res) {
var h = req.headers['x-test-key']
hits[h] = true
pending --
if (pending === 0) done()
})
}}
for (var i = 0; i < 5; i ++) {
pending ++
var val = 'test_' + i
expect[val] = true
request({ url: (i % 2 ? sUrl : ssUrl) + '/a'
, headers: { 'x-test-key': val }
, rejectUnauthorized: false })
}
function done () {
assert.deepEqual(hits, expect)
process.exit(0)
}

View File

@@ -0,0 +1,39 @@
var server = require('./server')
, events = require('events')
, stream = require('stream')
, assert = require('assert')
, fs = require('fs')
, request = require('../index')
, path = require('path')
, util = require('util')
;
var port = 6768
, called = false
, proxiedHost = 'google.com'
;
var s = server.createServer(port)
s.listen(port, function () {
s.on('http://google.com/', function (req, res) {
called = true
assert.equal(req.headers.host, proxiedHost)
res.writeHeader(200)
res.end()
})
request ({
url: 'http://'+proxiedHost,
proxy: 'http://localhost:'+port
/*
//should behave as if these arguments where passed:
url: 'http://localhost:'+port,
headers: {host: proxiedHost}
//*/
}, function (err, res, body) {
s.close()
})
})
process.on('exit', function () {
assert.ok(called, 'the request must be made to the proxy server')
})

View File

@@ -0,0 +1,34 @@
var request = request = require('../index')
, assert = require('assert')
;
// Test adding a querystring
var req1 = request.get({ uri: 'http://www.google.com', qs: { q : 'search' }})
setTimeout(function() {
assert.equal('/?q=search', req1.path)
}, 1)
// Test replacing a querystring value
var req2 = request.get({ uri: 'http://www.google.com?q=abc', qs: { q : 'search' }})
setTimeout(function() {
assert.equal('/?q=search', req2.path)
}, 1)
// Test appending a querystring value to the ones present in the uri
var req3 = request.get({ uri: 'http://www.google.com?x=y', qs: { q : 'search' }})
setTimeout(function() {
assert.equal('/?x=y&q=search', req3.path)
}, 1)
// Test leaving a querystring alone
var req4 = request.get({ uri: 'http://www.google.com?x=y'})
setTimeout(function() {
assert.equal('/?x=y', req4.path)
}, 1)
// Test giving empty qs property
var req5 = request.get({ uri: 'http://www.google.com', qs: {}})
setTimeout(function(){
assert.equal('/', req5.path)
}, 1)

View File

@@ -0,0 +1,155 @@
var server = require('./server')
, assert = require('assert')
, request = require('../index')
, Cookie = require('cookie-jar')
, Jar = Cookie.Jar
;
var s = server.createServer()
s.listen(s.port, function () {
var server = 'http://localhost:' + s.port;
var hits = {}
var passed = 0;
bouncer(301, 'temp')
bouncer(302, 'perm')
bouncer(302, 'nope')
function bouncer(code, label) {
var landing = label+'_landing';
s.on('/'+label, function (req, res) {
hits[label] = true;
res.writeHead(code, {
'location':server + '/'+landing,
'set-cookie': 'ham=eggs'
})
res.end()
})
s.on('/'+landing, function (req, res) {
if (req.method !== 'GET') { // We should only accept GET redirects
console.error("Got a non-GET request to the redirect destination URL");
res.writeHead(400);
res.end();
return;
}
// Make sure the cookie doesn't get included twice, see #139:
// Make sure cookies are set properly after redirect
assert.equal(req.headers.cookie, 'foo=bar; quux=baz; ham=eggs');
hits[landing] = true;
res.writeHead(200)
res.end(landing)
})
}
// Permanent bounce
var jar = new Jar()
jar.add(new Cookie('quux=baz'))
request({uri: server+'/perm', jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.perm, 'Original request is to /perm')
assert.ok(hits.perm_landing, 'Forward to permanent landing URL')
assert.equal(body, 'perm_landing', 'Got permanent landing content')
passed += 1
done()
})
// Temporary bounce
request({uri: server+'/temp', jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(hits.temp_landing, 'Forward to temporary landing URL')
assert.equal(body, 'temp_landing', 'Got temporary landing content')
passed += 1
done()
})
// Prevent bouncing.
request({uri:server+'/nope', jar: jar, headers: {cookie: 'foo=bar'}, followRedirect:false}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 302) throw new Error('Status is not 302: '+res.statusCode)
assert.ok(hits.nope, 'Original request to /nope')
assert.ok(!hits.nope_landing, 'No chasing the redirect')
assert.equal(res.statusCode, 302, 'Response is the bounce itself')
passed += 1
done()
})
// Should not follow post redirects by default
request.post(server+'/temp', { jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 301) throw new Error('Status is not 301: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect when post')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should follow post redirects when followAllRedirects true
request.post({uri:server+'/temp', followAllRedirects:true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(hits.temp_landing, 'Forward to temporary landing URL')
assert.equal(body, 'temp_landing', 'Got temporary landing content')
passed += 1
done()
})
request.post({uri:server+'/temp', followAllRedirects:false, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 301) throw new Error('Status is not 301: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should not follow delete redirects by default
request.del(server+'/temp', { jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode < 301) throw new Error('Status is not a redirect.')
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect when delete')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should not follow delete redirects even if followRedirect is set to true
request.del(server+'/temp', { followRedirect: true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 301) throw new Error('Status is not 301: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect when delete')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should follow delete redirects when followAllRedirects true
request.del(server+'/temp', {followAllRedirects:true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(hits.temp_landing, 'Forward to temporary landing URL')
assert.equal(body, 'temp_landing', 'Got temporary landing content')
passed += 1
done()
})
var reqs_done = 0;
function done() {
reqs_done += 1;
if(reqs_done == 9) {
console.log(passed + ' tests passed.')
s.close()
}
}
})

View File

@@ -0,0 +1,13 @@
var request = require('../index')
var r = request.get('https://log.curlybracecast.com.s3.amazonaws.com/',
{ aws:
{ key: 'AKIAI6KIQRRVMGK3WK5Q'
, secret: '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'
, bucket: 'log.curlybracecast.com'
}
}, function (e, resp, body) {
console.log(r.headers)
console.log(body)
}
)

View File

@@ -0,0 +1,87 @@
var server = require('./server')
, events = require('events')
, stream = require('stream')
, assert = require('assert')
, request = require('../index')
;
var s = server.createServer();
var expectedBody = "waited";
var remainingTests = 5;
s.listen(s.port, function () {
// Request that waits for 200ms
s.on('/timeout', function (req, resp) {
setTimeout(function(){
resp.writeHead(200, {'content-type':'text/plain'})
resp.write(expectedBody)
resp.end()
}, 200);
});
// Scenario that should timeout
var shouldTimeout = {
url: s.url + "/timeout",
timeout:100
}
request(shouldTimeout, function (err, resp, body) {
assert.equal(err.code, "ETIMEDOUT");
checkDone();
})
// Scenario that shouldn't timeout
var shouldntTimeout = {
url: s.url + "/timeout",
timeout:300
}
request(shouldntTimeout, function (err, resp, body) {
assert.equal(err, null);
assert.equal(expectedBody, body)
checkDone();
})
// Scenario with no timeout set, so shouldn't timeout
var noTimeout = {
url: s.url + "/timeout"
}
request(noTimeout, function (err, resp, body) {
assert.equal(err);
assert.equal(expectedBody, body)
checkDone();
})
// Scenario with a negative timeout value, should be treated a zero or the minimum delay
var negativeTimeout = {
url: s.url + "/timeout",
timeout:-1000
}
request(negativeTimeout, function (err, resp, body) {
assert.equal(err.code, "ETIMEDOUT");
checkDone();
})
// Scenario with a float timeout value, should be rounded by setTimeout anyway
var floatTimeout = {
url: s.url + "/timeout",
timeout: 100.76
}
request(floatTimeout, function (err, resp, body) {
assert.equal(err.code, "ETIMEDOUT");
checkDone();
})
function checkDone() {
if(--remainingTests == 0) {
s.close();
console.log("All tests passed.");
}
}
})

View File

@@ -0,0 +1,14 @@
var request = require('../index')
, http = require('http')
, assert = require('assert')
;
var s = http.createServer(function (req, resp) {
resp.statusCode = 200
resp.end('asdf')
}).listen(8080, function () {
var r = request('http://localhost:8080', function (e, resp) {
assert.equal(JSON.parse(JSON.stringify(r)).response.statusCode, 200)
s.close()
})
})

View File

@@ -0,0 +1,63 @@
// test that we can tunnel a https request over an http proxy
// keeping all the CA and whatnot intact.
//
// Note: this requires that squid is installed.
// If the proxy fails to start, we'll just log a warning and assume success.
var server = require('./server')
, assert = require('assert')
, request = require('../index')
, fs = require('fs')
, path = require('path')
, caFile = path.resolve(__dirname, 'ssl/npm-ca.crt')
, ca = fs.readFileSync(caFile)
, child_process = require('child_process')
, sqConf = path.resolve(__dirname, 'squid.conf')
, sqArgs = ['-f', sqConf, '-N', '-d', '5']
, proxy = 'http://localhost:3128'
, hadError = null
var squid = child_process.spawn('squid', sqArgs);
var ready = false
squid.stderr.on('data', function (c) {
console.error('SQUIDERR ' + c.toString().trim().split('\n')
.join('\nSQUIDERR '))
ready = c.toString().match(/ready to serve requests|Accepting HTTP Socket connections/i)
})
squid.stdout.on('data', function (c) {
console.error('SQUIDOUT ' + c.toString().trim().split('\n')
.join('\nSQUIDOUT '))
})
squid.on('exit', function (c) {
console.error('squid: exit '+c)
if (c && !ready) {
console.error('squid must be installed to run this test.')
console.error('skipping this test. please install squid and run again if you need to test tunneling.')
c = null
hadError = null
process.exit(0)
return
}
if (c) {
hadError = hadError || new Error('Squid exited with '+c)
}
if (hadError) throw hadError
})
setTimeout(function F () {
if (!ready) return setTimeout(F, 100)
request({ uri: 'https://registry.npmjs.org/'
, proxy: 'http://localhost:3128'
, strictSSL: true
, ca: ca
, json: true }, function (er, body) {
hadError = er
console.log(er || typeof body)
if (!er) console.log("ok")
squid.kill('SIGKILL')
})
}, 100)

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB