RateLimiterTests.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const SandboxedModule = require('sandboxed-module')
  2. const sinon = require('sinon')
  3. const { expect } = require('chai')
  4. const modulePath = require('path').join(
  5. __dirname,
  6. '../../../../app/src/infrastructure/RateLimiter'
  7. )
  8. describe('RateLimiter', function () {
  9. beforeEach(function () {
  10. this.rclient = {}
  11. this.RedisWrapper = {
  12. client: sinon.stub().returns(this.rclient),
  13. }
  14. this.RateLimiter = {
  15. RateLimiter: sinon.stub().withArgs('login').returns(this.rateLimiter),
  16. }
  17. this.RateLimiterFlexible = {
  18. RateLimiterRedis: sinon.stub(),
  19. }
  20. this.RateLimiter = SandboxedModule.require(modulePath, {
  21. requires: {
  22. './RedisWrapper': this.RedisWrapper,
  23. 'rate-limiter-flexible': this.RateLimiterFlexible,
  24. },
  25. })
  26. })
  27. describe('getSubnetKeyFromIp', function () {
  28. beforeEach(function () {
  29. this.rateLimiter = new this.RateLimiter.RateLimiter('some-limit', {
  30. points: 20,
  31. subnetPoints: 200,
  32. duration: 60,
  33. })
  34. })
  35. it('should correctly extract a subnet key from an ip address', function () {
  36. expect(this.rateLimiter.getSubnetKeyFromIp('255.255.255.255')).to.equal(
  37. '255.255.255'
  38. )
  39. expect(this.rateLimiter.getSubnetKeyFromIp('127.0.0.1')).to.equal(
  40. '127.0.0'
  41. )
  42. expect(this.rateLimiter.getSubnetKeyFromIp('243.12.3.126')).to.equal(
  43. '243.12.3'
  44. )
  45. })
  46. it('should throw an error when given an incorrectly formatted ip', function () {
  47. expect(() => this.rateLimiter.getSubnetKeyFromIp(1)).to.throw()
  48. expect(() => this.rateLimiter.getSubnetKeyFromIp('Not an ip')).to.throw()
  49. expect(() =>
  50. this.rateLimiter.getSubnetKeyFromIp('255.255.255.255.255.255')
  51. ).to.throw()
  52. expect(() =>
  53. this.rateLimiter.getSubnetKeyFromIp('255.255.255')
  54. ).to.throw()
  55. })
  56. })
  57. })