init commit

This commit is contained in:
rainbownapkin 2021-12-06 19:56:40 -05:00
parent ae639426d0
commit 7a491681cc
257 changed files with 95524 additions and 80 deletions

18
test/util/hash.js Normal file
View file

@ -0,0 +1,18 @@
const { hash } = require('../../lib/util/hash');
const assert = require('assert');
describe('hash', () => {
describe('#hash', () => {
const input = 'this is a test';
it('hashes input correctly', () => {
const sha256_hex = '2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c';
assert.strictEqual(hash('sha256', input, 'hex'), sha256_hex);
});
it('hashes input to base64', () => {
const sha256_base64 = 'Lpl1hUiXKo6IIq1H+hAX/3Lwbz/2oBaFH0XDmHMrxQw=';
assert.strictEqual(hash('sha256', input, 'base64'), sha256_base64);
});
});
});

66
test/util/token-bucket.js Normal file
View file

@ -0,0 +1,66 @@
const assert = require('assert');
const TokenBucket = require('../../lib/util/token-bucket').TokenBucket;
describe('TokenBucket', () => {
describe('#throttle', () => {
let bucket;
beforeEach(() => {
bucket = new TokenBucket(5, 5);
});
it('consumes capacity and then throttles', () => {
assert(!bucket.throttle(), 'should not be empty yet');
assert(!bucket.throttle(), 'should not be empty yet');
assert(!bucket.throttle(), 'should not be empty yet');
assert(!bucket.throttle(), 'should not be empty yet');
assert(!bucket.throttle(), 'should not be empty yet');
assert(bucket.throttle(), 'should be empty now');
});
it('refills tokens', () => {
bucket.count = 0;
const oldRefill = bucket.lastRefill = Date.now() - 1000;
assert(!bucket.throttle(), 'should have refilled');
assert(bucket.lastRefill >= oldRefill + 1000, 'should have updated lastRefill');
});
it('refills at most {capacity} tokens', () => {
bucket.count = 0;
bucket.lastRefill = Date.now() - 10000;
bucket.throttle();
assert.strictEqual(bucket.count, 4);
});
it('does a partial refill', () => {
bucket.count = 0;
bucket.lastRefill = Date.now() - 400;
bucket.throttle();
assert.strictEqual(bucket.count, 1);
});
it('skips refilling if delta = 0', () => {
bucket.count = 0;
const oldRefill = bucket.lastRefill;
bucket.throttle();
assert.strictEqual(bucket.count, 0);
assert.strictEqual(bucket.lastRefill, oldRefill);
});
it('handles fractional refill rates', () => {
bucket = new TokenBucket(5, 0.1);
bucket.count = 0;
assert(bucket.throttle());
bucket.lastRefill = Date.now() - 10000;
assert(!bucket.throttle());
assert.strictEqual(bucket.count, 0);
});
it('handles infinite refill rate and capacity', () => {
bucket = new TokenBucket(Infinity, Infinity);
for (let i = 0; i < 100; i++) {
assert(!bucket.throttle(), 'should not throttle');
}
});
});
});