-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtest.js
83 lines (65 loc) · 2.04 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
var assert = require('assert');
var after = require('after');
var rateLimit = require('./');
test('should only allow one call per interval', function (done) {
var start = Date.now();
// time that passes is 400ms since the first call executes immediate
var expected = [0, 100, 200, 300, 400];
var offsets = [];
var trigger = after(5, function() {
fuzzy_compare(expected, offsets)
done();
});
var fn = rateLimit(1, 100, function() {
offsets.push(Date.now() - start);
trigger();
});
for (var i = 0; i < 5; ++i) {
fn(i);
}
});
test('should allow for calls to burst', function (done) {
var start = Date.now();
var expected = [0, 0, 100, 100, 200];
var offsets = [];
// time that passes is 400ms since the first call executes immediate
var trigger = after(5, function() {
fuzzy_compare(expected, offsets)
done();
});
var fn = rateLimit(2, 100, function() {
offsets.push(Date.now() - start);
trigger();
});
for (var i = 0; i < 5; ++i) {
fn(i);
}
});
test('should preserve function context', function (done) {
var start = Date.now();
// time that passes is 400ms since the first call executes immediate
var expected = [0, 100, 200, 300, 400];
var offsets = [];
var trigger = after(5, function() {
fuzzy_compare(expected, offsets)
done();
});
var fn = rateLimit(1, 100, function() {
assert(this.foo === 'bar');
offsets.push(Date.now() - start);
trigger();
});
for (var i = 0; i < 5; ++i) {
fn.call({ foo: 'bar' }, i);
}
});
function fuzzy_compare(expected, actual) {
assert.equal(expected.length, actual.length);
expected.forEach(function(expected_value, idx) {
var actual_val = actual[idx];
var diff = Math.abs(expected_value - actual_val);
if (diff > 20) {
throw new Error('actual and expected values differ too much: actual ' + actual_val + ' != ' + expected_value);
}
});
}