-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
122 lines (102 loc) · 2.27 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
'use strict';
const test = require('tape');
const stopcock = require('.');
test('is exported as a function', (t) => {
t.equal(typeof stopcock, 'function');
t.end();
});
test('returns a function that returns a promise', (t) => {
const limit = stopcock(() => 'foo');
limit().then((value) => {
t.equal(value, 'foo');
t.end();
});
});
test('calls the original function with the same context and arguments', (t) => {
const limit = stopcock(function() {
t.deepEqual(
arguments,
(function() {
return arguments;
})(1, 2)
);
t.equal(this, 'foo');
});
limit.call('foo', 1, 2).then(t.end);
});
test('allows to limit the queue size', (t) => {
const limit = stopcock(() => {}, {
bucketSize: 1,
interval: 100,
queueSize: 2,
limit: 1
});
limit();
limit();
limit();
limit().then(
() => {
t.fail('Promise should not be fulfilled');
t.end();
},
(err) => {
t.equal(err instanceof Error, true);
t.equal(err.message, 'Queue is full');
t.end();
}
);
});
test('allows to inspect the queue size', (t) => {
const limit = stopcock(() => {}, {
bucketSize: 1,
interval: 50,
limit: 1
});
limit();
t.equal(limit.size, 0);
limit().then(() => {
t.equal(limit.size, 0);
t.end();
});
t.equal(limit.size, 1);
});
test('limits the execution rate of the original function', (t) => {
const values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const start = Date.now();
const times = [];
const limit = stopcock(
(arg) => {
times.push(Date.now());
return Promise.resolve(arg);
},
{
bucketSize: 4,
interval: 200,
limit: 2
}
);
Promise.all(values.map((i) => limit(i))).then((data) => {
t.deepEqual(data, values);
times.forEach((time, i) => {
const delay = i < 4 ? 0 : (i - 3) * 100;
const diff = time - start - delay;
t.ok(diff >= 0 && diff < 20);
});
t.end();
});
});
test('prevents the bucket from going over capacity', (t) => {
const limit = stopcock(() => Date.now(), {
bucketSize: 1,
interval: 50,
limit: 1
});
setTimeout(() => {
const start = Date.now();
limit();
limit().then((now) => {
t.ok(now - start >= 50);
t.end();
});
}, 150);
});