Skip to content

Commit

Permalink
🚧 progress: Refactor tests SUQASH.
Browse files Browse the repository at this point in the history
  • Loading branch information
make-github-pseudonymous-again committed May 21, 2024
1 parent 1eba66d commit 18bf0cc
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions server/api/rateLimit.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@ import sleep from '../../imports/lib/async/sleep';
import {RateLimiterMemory, pipe} from './rateLimit';
import {createRouter} from './route';

const _repeat = <T>(n: number, fn: () => T) =>
Array.from({length: n}).map(() => fn());

server(__filename, () => {
it.only('should not rate-limit burts below quota', async () => {
const routes = createRouter();
const points = 10;
const duration = 60;

const rateLimiter = new RateLimiterMemory({
// NOTE key prefix is not necessary since each RateLimiterMemory is backed
// by its own storage.
keyPrefix: '',
points: 3,
points,
duration,
});

Expand All @@ -35,7 +39,7 @@ server(__filename, () => {

const start = new Date();

const responses = await Promise.all([send(), send(), send()]);
const responses = await Promise.all(_repeat(points, send));

const stop = new Date();

Expand All @@ -45,18 +49,19 @@ server(__filename, () => {

const bodies = setLike(responses.map((res) => res.text));

assert.deepEqual(bodies, setLike(['OK', 'OK', 'OK']));
assert.deepEqual(bodies, setLike(_repeat(points, () => 'OK')));
});

it.only('should rate-limit bursts above quota', async () => {
const routes = createRouter();
const points = 2;
const duration = 60;

const rateLimiter = new RateLimiterMemory({
// NOTE key prefix is not necessary since each RateLimiterMemory is backed
// by its own storage.
keyPrefix: '',
points: 2,
points,
duration,
});

Expand All @@ -74,7 +79,7 @@ server(__filename, () => {

const start = new Date();

const responses = await Promise.all([send(), send(), send()]);
const responses = await Promise.all(_repeat(points + 1, send));

const stop = new Date();

Expand All @@ -84,11 +89,17 @@ server(__filename, () => {

const statuses = setLike(responses.map((res) => res.status));

assert.deepEqual(statuses, setLike([200, 200, 429]));
assert.deepEqual(
statuses,
setLike(_repeat(points, () => 200).concat([429])),
);

const bodies = setLike(responses.map((res) => res.text));

assert.deepEqual(bodies, setLike(['OK', 'OK', 'Too Many Requests']));
assert.deepEqual(
bodies,
setLike(_repeat(points, () => 'OK').concat(['Too Many Requests'])),
);
});

// TODO Test above quota without a burst.
Expand Down

0 comments on commit 18bf0cc

Please sign in to comment.