RateLimitManager.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "./Metrics": @Metrics =
  13. Timer: class Timer
  14. done: sinon.stub()
  15. gauge: sinon.stub()
  16. @callback = sinon.stub()
  17. @RateLimiter = new @RateLimitManager(1)
  18. describe "for a single task", ->
  19. beforeEach ->
  20. @task = sinon.stub()
  21. @RateLimiter.run @task, @callback
  22. it "should execute the task in the background", ->
  23. @task.called.should.equal true
  24. it "should call the callback", ->
  25. @callback.called.should.equal true
  26. it "should finish with a worker count of one", ->
  27. # because it's in the background
  28. expect(@RateLimiter.ActiveWorkerCount).to.equal 1
  29. describe "for multiple tasks", ->
  30. beforeEach (done) ->
  31. @task = sinon.stub()
  32. @finalTask = sinon.stub()
  33. task = (cb) =>
  34. @task()
  35. setTimeout cb, 100
  36. finalTask = (cb) =>
  37. @finalTask()
  38. setTimeout cb, 100
  39. @RateLimiter.run task, @callback
  40. @RateLimiter.run task, @callback
  41. @RateLimiter.run task, @callback
  42. @RateLimiter.run finalTask, (err) =>
  43. @callback(err)
  44. done()
  45. it "should execute the first three tasks", ->
  46. @task.calledThrice.should.equal true
  47. it "should execute the final task", ->
  48. @finalTask.called.should.equal true
  49. it "should call the callback", ->
  50. @callback.called.should.equal true
  51. it "should finish with worker count of zero", ->
  52. expect(@RateLimiter.ActiveWorkerCount).to.equal 0
  53. describe "for a mixture of long-running tasks", ->
  54. beforeEach (done) ->
  55. @task = sinon.stub()
  56. @finalTask = sinon.stub()
  57. finalTask = (cb) =>
  58. @finalTask()
  59. setTimeout cb, 100
  60. @RateLimiter.run @task, @callback
  61. @RateLimiter.run @task, @callback
  62. @RateLimiter.run @task, @callback
  63. @RateLimiter.run finalTask, (err) =>
  64. @callback(err)
  65. done()
  66. it "should execute the first three tasks", ->
  67. @task.calledThrice.should.equal true
  68. it "should execute the final task", ->
  69. @finalTask.called.should.equal true
  70. it "should call the callback", ->
  71. @callback.called.should.equal true
  72. it "should finish with worker count of three", ->
  73. expect(@RateLimiter.ActiveWorkerCount).to.equal 3