RateLimterTests.coffee 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. assert = require("chai").assert
  2. sinon = require('sinon')
  3. chai = require('chai')
  4. should = chai.should()
  5. expect = chai.expect
  6. modulePath = "../../../../app/js/infrastructure/RateLimiter.js"
  7. SandboxedModule = require('sandboxed-module')
  8. describe "RateLimiter", ->
  9. beforeEach ->
  10. @settings =
  11. redis:
  12. web:
  13. port:"1234"
  14. host:"somewhere"
  15. password: "password"
  16. @rclient =
  17. incr: sinon.stub()
  18. get: sinon.stub()
  19. expire: sinon.stub()
  20. exec: sinon.stub()
  21. @rclient.multi = sinon.stub().returns(@rclient)
  22. @RedisWrapper =
  23. client: sinon.stub().returns(@rclient)
  24. @limiterFn = sinon.stub()
  25. @RollingRateLimiter = (opts) =>
  26. return @limiterFn
  27. @limiter = SandboxedModule.require modulePath, requires:
  28. "rolling-rate-limiter": @RollingRateLimiter
  29. "settings-sharelatex":@settings
  30. "logger-sharelatex" : @logger = {log:sinon.stub(), err:sinon.stub()}
  31. "./RedisWrapper": @RedisWrapper
  32. @endpointName = "compiles"
  33. @subject = "some-project-id"
  34. @timeInterval = 20
  35. @throttleLimit = 5
  36. @details =
  37. endpointName: @endpointName
  38. subjectName: @subject
  39. throttle: @throttleLimit
  40. timeInterval: @timeInterval
  41. @key = "RateLimiter:#{@endpointName}:{#{@subject}}"
  42. describe 'when action is permitted', ->
  43. beforeEach ->
  44. @limiterFn = sinon.stub().callsArgWith(1, null, 0, 22)
  45. it 'should not produce and error', (done) ->
  46. @limiter.addCount {}, (err, should) ->
  47. expect(err).to.equal null
  48. done()
  49. it 'should callback with true', (done) ->
  50. @limiter.addCount {}, (err, should) ->
  51. expect(should).to.equal true
  52. done()
  53. describe 'when action is not permitted', ->
  54. beforeEach ->
  55. @limiterFn = sinon.stub().callsArgWith(1, null, 4000, 0)
  56. it 'should not produce and error', (done) ->
  57. @limiter.addCount {}, (err, should) ->
  58. expect(err).to.equal null
  59. done()
  60. it 'should callback with false', (done) ->
  61. @limiter.addCount {}, (err, should) ->
  62. expect(should).to.equal false
  63. done()
  64. describe 'when limiter produces an error', ->
  65. beforeEach ->
  66. @limiterFn = sinon.stub().callsArgWith(1, new Error('woops'))
  67. it 'should produce and error', (done) ->
  68. @limiter.addCount {}, (err, should) ->
  69. expect(err).to.not.equal null
  70. expect(err).to.be.instanceof Error
  71. done()