RateLimitManager.coffee 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. sinon = require('sinon')
  2. chai = require('chai')
  3. should = chai.should()
  4. expect = chai.expect
  5. modulePath = "../../../../app/js/RateLimitManager.js"
  6. SandboxedModule = require('sandboxed-module')
  7. describe "RateLimitManager", ->
  8. beforeEach ->
  9. @RateLimitManager = SandboxedModule.require modulePath, requires:
  10. "logger-sharelatex": @logger = { log: sinon.stub() }
  11. "settings-sharelatex": @settings =
  12. redis:
  13. realtime: {}
  14. "./Metrics": @Metrics =
  15. Timer: class Timer
  16. done: sinon.stub()
  17. gauge: sinon.stub()
  18. @callback = sinon.stub()
  19. @RateLimiter = new @RateLimitManager(1)
  20. describe "for a single task", ->
  21. beforeEach ->
  22. @task = sinon.stub()
  23. @RateLimiter.run @task, @callback
  24. it "should execute the task in the background", ->
  25. @task.called.should.equal true
  26. it "should call the callback", ->
  27. @callback.called.should.equal true
  28. it "should finish with a worker count of one", ->
  29. # because it's in the background
  30. expect(@RateLimiter.ActiveWorkerCount).to.equal 1
  31. describe "for multiple tasks", ->
  32. beforeEach (done) ->
  33. @task = sinon.stub()
  34. @finalTask = sinon.stub()
  35. task = (cb) =>
  36. @task()
  37. setTimeout cb, 100
  38. finalTask = (cb) =>
  39. @finalTask()
  40. setTimeout cb, 100
  41. @RateLimiter.run task, @callback
  42. @RateLimiter.run task, @callback
  43. @RateLimiter.run task, @callback
  44. @RateLimiter.run finalTask, (err) =>
  45. @callback(err)
  46. done()
  47. it "should execute the first three tasks", ->
  48. @task.calledThrice.should.equal true
  49. it "should execute the final task", ->
  50. @finalTask.called.should.equal true
  51. it "should call the callback", ->
  52. @callback.called.should.equal true
  53. it "should finish with worker count of zero", ->
  54. expect(@RateLimiter.ActiveWorkerCount).to.equal 0
  55. describe "for a mixture of long-running tasks", ->
  56. beforeEach (done) ->
  57. @task = sinon.stub()
  58. @finalTask = sinon.stub()
  59. finalTask = (cb) =>
  60. @finalTask()
  61. setTimeout cb, 100
  62. @RateLimiter.run @task, @callback
  63. @RateLimiter.run @task, @callback
  64. @RateLimiter.run @task, @callback
  65. @RateLimiter.run finalTask, (err) =>
  66. @callback(err)
  67. done()
  68. it "should execute the first three tasks", ->
  69. @task.calledThrice.should.equal true
  70. it "should execute the final task", ->
  71. @finalTask.called.should.equal true
  72. it "should call the callback", ->
  73. @callback.called.should.equal true
  74. it "should finish with worker count of three", ->
  75. expect(@RateLimiter.ActiveWorkerCount).to.equal 3