|
| 1 | +/*! |
| 2 | + * Copyright (c) Microsoft Corporation and contributors. All rights reserved. |
| 3 | + * Licensed under the MIT License. |
| 4 | + */ |
| 5 | + |
| 6 | +import assert from "assert"; |
| 7 | +import express from "express"; |
| 8 | +import request from "supertest"; |
| 9 | +import { ResponseSizeMiddleware } from "../responseSizeMiddleware"; |
| 10 | + |
| 11 | +describe("Throttler Middleware", () => { |
| 12 | + const endpoint = "/test"; |
| 13 | + const route = `${endpoint}/:id?`; |
| 14 | + let responseSizeMiddleware: ResponseSizeMiddleware; |
| 15 | + const responseMaxSizeInMb = 1; // 1MB |
| 16 | + let app: express.Application; |
| 17 | + let supertest: request.SuperTest<request.Test>; |
| 18 | + const setUpRoute = (data: any, subPath?: string): void => { |
| 19 | + const routePath = `${route}${subPath ? `/${subPath}` : ""}`; |
| 20 | + app.get(routePath, (req, res) => { |
| 21 | + res.status(200).send(data); |
| 22 | + }); |
| 23 | + }; |
| 24 | + beforeEach(() => { |
| 25 | + app = express(); |
| 26 | + responseSizeMiddleware = new ResponseSizeMiddleware(responseMaxSizeInMb); |
| 27 | + app.use(responseSizeMiddleware.validateResponseSize()); |
| 28 | + }); |
| 29 | + |
| 30 | + describe("validateResponseSize", () => { |
| 31 | + it("sends 200 when limit not exceeded", async () => { |
| 32 | + setUpRoute("test"); |
| 33 | + supertest = request(app); |
| 34 | + await supertest.get(endpoint).expect((res) => { |
| 35 | + assert.strictEqual(res.status, 200); |
| 36 | + }); |
| 37 | + }); |
| 38 | + |
| 39 | + it("sends 413 with message when response size is greate than max response size", async () => { |
| 40 | + const sizeInBytes = 5 * 1024 * 1024; // 5MB |
| 41 | + const largeObject = { |
| 42 | + data: "a".repeat(sizeInBytes), |
| 43 | + }; |
| 44 | + setUpRoute(largeObject); |
| 45 | + supertest = request(app); |
| 46 | + await supertest.get(endpoint).expect((res) => { |
| 47 | + assert.strictEqual(res.status, 413); |
| 48 | + assert.strictEqual(res.body.error, "Response too large"); |
| 49 | + assert.strictEqual( |
| 50 | + res.body.message, |
| 51 | + `Response size exceeds the maximum allowed size of ${responseMaxSizeInMb} megabytes`, |
| 52 | + ); |
| 53 | + }); |
| 54 | + }); |
| 55 | + }); |
| 56 | +}); |
0 commit comments