|
| 1 | +const sinon = require("sinon"); |
| 2 | +const { TOO_MANY_REQUESTS } = require("../../../constants/rateLimiting"); |
| 3 | +const { commonRateLimiter } = require("../../../middlewares/rateLimiting"); |
| 4 | + |
| 5 | +function mockRequest(ipAddress) { |
| 6 | + return { |
| 7 | + headers: { |
| 8 | + "x-forwarded-for": ipAddress, |
| 9 | + }, |
| 10 | + socket: { |
| 11 | + remoteAddress: ipAddress, |
| 12 | + }, |
| 13 | + }; |
| 14 | +} |
| 15 | + |
| 16 | +function mockResponse(sandbox) { |
| 17 | + const res = {}; |
| 18 | + res.status = sandbox.stub().returns(res); |
| 19 | + res.json = sandbox.stub().returns(res); |
| 20 | + res.set = sandbox.stub().returns(res); |
| 21 | + return res; |
| 22 | +} |
| 23 | + |
| 24 | +describe("Rate Limting Middelware", function () { |
| 25 | + let req; |
| 26 | + let res; |
| 27 | + let next; |
| 28 | + let sandbox; |
| 29 | + |
| 30 | + beforeEach(function () { |
| 31 | + sandbox = sinon.createSandbox(); |
| 32 | + req = mockRequest("127.0.0.1"); |
| 33 | + res = mockResponse(sandbox); |
| 34 | + next = sandbox.stub(); |
| 35 | + }); |
| 36 | + |
| 37 | + afterEach(function () { |
| 38 | + sandbox.restore(); |
| 39 | + }); |
| 40 | + |
| 41 | + it("Should call the next middelware if the request count is under the limit", async function () { |
| 42 | + await commonRateLimiter(req, res, next); |
| 43 | + sinon.assert.calledOnce(next); |
| 44 | + }); |
| 45 | + |
| 46 | + it("Should return 429 status code and message `Too many requests` if the request count exceeds the limit", async function () { |
| 47 | + const promises = []; |
| 48 | + for (let index = 0; index < 10; ++index) { |
| 49 | + const promise = commonRateLimiter(req, res, next); |
| 50 | + promises.push(promise); |
| 51 | + } |
| 52 | + await Promise.all(promises); |
| 53 | + sinon.assert.calledWithMatch(res.status, TOO_MANY_REQUESTS.STATUS_CODE); |
| 54 | + }); |
| 55 | + |
| 56 | + it("Should reset the request count after duration has passed", async function () { |
| 57 | + const promises = []; |
| 58 | + for (let index = 0; index < 10; ++index) { |
| 59 | + const promise = commonRateLimiter(req, res, next); |
| 60 | + promises.push(promise); |
| 61 | + } |
| 62 | + await Promise.all(promises); |
| 63 | + sinon.assert.calledWithMatch(res.status, TOO_MANY_REQUESTS.STATUS_CODE); |
| 64 | + |
| 65 | + /** |
| 66 | + INFO[no-reasoning-only-assumption]: |
| 67 | + using setTimeout instead of sinon.FakeTimers, |
| 68 | + because clock was ticking for expected duration but |
| 69 | + key was not getting deleted from middelware store |
| 70 | + */ |
| 71 | + setTimeout(async () => { |
| 72 | + await commonRateLimiter(req, res, next); |
| 73 | + sinon.assert.neverCalledWithMatch(res.status, TOO_MANY_REQUESTS.STATUS_CODE); |
| 74 | + sinon.assert.calledOnce(next); |
| 75 | + }, 1000); |
| 76 | + }); |
| 77 | +}); |
0 commit comments