-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-original.js
85 lines (67 loc) · 1.97 KB
/
test-original.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
/* global test */
'use strict';
const assert = require('assert');
const after = require('after');
const rateLimit = require('./');
test('should only allow one call per interval', function (done) {
const start = Date.now();
// time that passes is 400ms since the first call executes immediate
const expected = [0, 100, 200, 300, 400];
const offsets = [];
const trigger = after(5, function() {
fuzzy_compare(expected, offsets);
done();
});
const fn = rateLimit(1, 100, function() {
offsets.push(Date.now() - start);
trigger();
});
for (let i = 0; i < 5; ++i) {
fn(i);
}
});
test('should allow for calls to burst', function (done) {
const start = Date.now();
const expected = [0, 0, 100, 100, 200];
const offsets = [];
// time that passes is 400ms since the first call executes immediate
const trigger = after(5, function() {
fuzzy_compare(expected, offsets);
done();
});
const fn = rateLimit(2, 100, function() {
offsets.push(Date.now() - start);
trigger();
});
for (let i = 0; i < 5; ++i) {
fn(i);
}
});
test('should preserve function context', function (done) {
const start = Date.now();
// time that passes is 400ms since the first call executes immediate
const expected = [0, 100, 200, 300, 400];
const offsets = [];
const trigger = after(5, function() {
fuzzy_compare(expected, offsets);
done();
});
const fn = rateLimit(1, 100, function() {
assert(this.foo === 'bar');
offsets.push(Date.now() - start);
trigger();
});
for (let 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) {
const actual_val = actual[idx];
const 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);
}
});
}