-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtestboot.js
93 lines (71 loc) · 2.07 KB
/
testboot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
if(!module.parent) {
return console.log("To run the tests verbosely, use `mocha --reporter spec`");
}
/**
* Boot the app for tests, and export some helpers
*/
var boot = require('./boot.js'),
http = require('http');
exports.app = app = boot.app;
exports.kit = boot.kit;
exports.helper = {
serverListen: function(done) {
if(!app.address()) {
app.listen(3001, function() {
console.log("[test] serverListen on port %d in %s mode", app.address().port, app.settings.env);
setTimeout(done, 100); // FIXME - wait a bit for everything to warm up
});
}
else done();
},
serverStop: function(done) {
app.close();
console.log("[test] serverStop");
done();
},
localRequest: localRequest // poor-man's assert.response
};
function localRequest(what, opts, callback) {
if(!callback) {
callback = opts;
opts = {};
}
var data = opts.data || null,
address = boot.app.address();
if(!address) throw 'localRequest needs a listening server!!!';
var m = what.match(/^(GET|POST|DELETE|PUT)\s+(\/[\w\-\/\.]*).*?$/),
mPath = m && m[2];
if(!mPath) throw 'localRequest needs a path or parsable context!!!';
var method = (m && m[1]) || (data&&'POST') || 'GET';
console.log("[test] localRequest: %s %s", method, mPath);
var request = http.request({
host: '127.0.0.1',
port: address.port,
path: mPath,
method: method
});
if(opts.cookie) {
request.setHeader("Cookie", opts.cookie);
}
request.on('response', function(response){
response.body = '';
response.on('data', function(chunk){ response.body += chunk; });
response.on('end', function(){
callback(response);
});
});
if(data) {
if(method=='GET'){
var q = [], p = request.path;
for (var k in data) {
q.push(k + '=' + encodeURIComponent(data[k]));
};
request.path = p + (p.match(/\?/) ? '&' : '?') + q.join('&');
}
else {
request.setHeader("Content-Type", "application/json");
request.write(JSON.stringify(data));
}
}
request.end();
}