-
Notifications
You must be signed in to change notification settings - Fork 2
/
sink-test.js
79 lines (73 loc) · 2.13 KB
/
sink-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
// the sink takes a source stream and calls it with a cb
// the cb gets passed `end` and `data` params from the source stream
// if the callback gets a truthy end param, it must not call source again
// if end is falsy, the cb can call source again, which signals that
// the sink is ready for a new event
function SinkTest (test, sink) {
test('Source emits end', function (t) {
sink()(End(t))
})
test('Source emits error', function (t) {
sink()(Err(t))
})
test('Async source', function (t) {
sink()(AsyncSource(t))
})
}
function End (t, count) {
count = count || 0
var ended = false
var i = 0
function source (abort, next) {
if (abort) t.fail('sink aborted before test finished')
if (ended) t.fail('should not call source after end')
if (i === count) {
ended = true
next(true)
return t.end()
}
next(null, i++)
}
return source
}
function Err (t, count) {
count = count || 0
var errd = false
var i = 0
function source (abort, next) {
if (abort) t.fail('sink aborted before test finished')
if (errd) t.fail('should not call source after error')
if (i === count) {
errd = true
next(new Error('test'))
return t.end()
}
next(null, i++)
}
return source
}
function AsyncSource (t, count) {
count = count || 0
var ended = false
var isResolving = false
var i = 0
return function asyncSource (abort, emitNext) {
if (abort) t.fail('sink aborted before the test finished')
if (ended) t.fail('should not call source after end')
if (isResolving) t.fail('source was called out of turn')
if (i === count) return process.nextTick(function () {
ended = true
emitNext(true)
t.end()
})
isResolving = true
process.nextTick(function () {
isResolving = false
emitNext(null, i++)
})
}
}
module.exports = SinkTest
module.exports.End = End
module.exports.Err = Err
module.exports.AsyncSource = AsyncSource