-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.js
125 lines (111 loc) · 2.47 KB
/
test.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
var respond = require('./');
var test = require('tap').test;
var Writable = require('stream').Writable;
var co = require('co');
var http = require('http');
var respond = require('./');
var wait = require('co-wait');
var request = require('supertest');
var through = require('through');
test('throws', function(t){
var called = 0;
var ended = 0;
var responded = false;
function throws(){
return function*(end){
if (end) return ended++;
called++;
throw new Error('oops');
}
}
var server = http.createServer(function(req, res){
co(function*(){
try {
yield respond(res, throws());
} catch (err) {
responded = true;
res.statusCode = 500;
res.end(err.message);
}
})();
});
request(server)
.get('/')
.expect(500)
.expect('oops', function(err){
t.error(err);
t.equal(called, 1, 'called once');
t.equal(ended, 1, 'ended once');
t.assert(responded);
server.close();
t.end();
});
});
test('ends', function(t){
var called = 0;
var ended = 0;
var responded = false;
function thrice(str){
var i = 0;
return function*(end){
if (end) return ended++;
called++;
if (i++ > 2) return;
yield wait(10);
return str;
}
}
var server = http.createServer(function(req, res){
co(function*(){
yield respond(res, thrice('bob'));
responded = true;
})();
});
request(server)
.get('/')
.expect(200)
.expect('bobbobbob', function(err){
setTimeout(function(){
t.error(err, 'sane');
t.equal(called, 4, 'called four times');
t.equal(ended, 1, 'ended once');
t.assert(responded, 'responded');
server.close();
t.end();
});
});
});
test('aborts', function(t){
var called = 0;
var ended = 0;
var responded = false;
function repeat(str){
return function*(end){
if (end) return ended++;
called++;
yield wait(10);
return str;
}
}
var server = http.createServer(function(req, res){
co(function*(){
yield respond(res, repeat('bob'));
responded = true;
})();
});
var req = request(server)
.get('/')
.expect(200);
req.pipe(through(function(data){
t.equal(data.toString(), 'bob');
req.abort();
}, function(){
setTimeout(function(){
t.equal(called, 2, 'called twice');
t.equal(ended, 1, 'ended once');
t.assert(responded, 'responded');
server.close();
t.end();
}, 100);
}));
});