RateLimterTests.coffee 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. @endpointName = "compiles"
  25. @subject = "some-project-id"
  26. @timeInterval = 20
  27. @throttleLimit = 5
  28. @requires =
  29. "settings-sharelatex":@settings
  30. "logger-sharelatex" : @logger = {log:sinon.stub(), err:sinon.stub()}
  31. "./RedisWrapper": @RedisWrapper
  32. @details =
  33. endpointName: @endpointName
  34. subjectName: @subject
  35. throttle: @throttleLimit
  36. timeInterval: @timeInterval
  37. @key = "RateLimiter:#{@endpointName}:{#{@subject}}"
  38. describe 'when action is permitted', ->
  39. beforeEach ->
  40. @requires["rolling-rate-limiter"] = (opts) =>
  41. return sinon.stub().callsArgWith(1, null, 0, 22)
  42. @limiter = SandboxedModule.require modulePath, requires: @requires
  43. it 'should not produce and error', (done) ->
  44. @limiter.addCount {}, (err, should) ->
  45. expect(err).to.equal null
  46. done()
  47. it 'should callback with true', (done) ->
  48. @limiter.addCount {}, (err, should) ->
  49. expect(should).to.equal true
  50. done()
  51. describe 'when action is not permitted', ->
  52. beforeEach ->
  53. @requires["rolling-rate-limiter"] = (opts) =>
  54. return sinon.stub().callsArgWith(1, null, 4000, 0)
  55. @limiter = SandboxedModule.require modulePath, requires: @requires
  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. @requires["rolling-rate-limiter"] = (opts) =>
  67. return sinon.stub().callsArgWith(1, new Error('woops'))
  68. @limiter = SandboxedModule.require modulePath, requires: @requires
  69. it 'should produce and error', (done) ->
  70. @limiter.addCount {}, (err, should) ->
  71. expect(err).to.not.equal null
  72. expect(err).to.be.instanceof Error
  73. done()