getLockTests.coffee 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. sinon = require('sinon')
  2. chai = require('chai')
  3. should = chai.should()
  4. modulePath = "../../../../app/js/LockManager.js"
  5. SandboxedModule = require('sandboxed-module')
  6. describe 'LockManager - getting the lock', ->
  7. beforeEach ->
  8. @LockManager = SandboxedModule.require modulePath, requires:
  9. "logger-sharelatex": log:->
  10. "redis-sharelatex":
  11. createClient : () =>
  12. auth:->
  13. "./Metrics": {inc: () ->}
  14. "./Profiler": class Profiler
  15. log: sinon.stub().returns { end: sinon.stub() }
  16. end: sinon.stub()
  17. @callback = sinon.stub()
  18. @doc_id = "doc-id-123"
  19. describe "when the lock is not set", ->
  20. beforeEach (done) ->
  21. @lockValue = "mock-lock-value"
  22. @LockManager.tryLock = sinon.stub().callsArgWith(1, null, true, @lockValue)
  23. @LockManager.getLock @doc_id, (args...) =>
  24. @callback(args...)
  25. done()
  26. it "should try to get the lock", ->
  27. @LockManager.tryLock
  28. .calledWith(@doc_id)
  29. .should.equal true
  30. it "should only need to try once", ->
  31. @LockManager.tryLock.callCount.should.equal 1
  32. it "should return the callback with the lock value", ->
  33. @callback.calledWith(null, @lockValue).should.equal true
  34. describe "when the lock is initially set", ->
  35. beforeEach (done) ->
  36. @lockValue = "mock-lock-value"
  37. startTime = Date.now()
  38. tries = 0
  39. @LockManager.LOCK_TEST_INTERVAL = 5
  40. @LockManager.tryLock = (doc_id, callback = (error, isFree) ->) =>
  41. if (Date.now() - startTime < 20) or (tries < 2)
  42. tries = tries + 1
  43. callback null, false
  44. else
  45. callback null, true, @lockValue
  46. sinon.spy @LockManager, "tryLock"
  47. @LockManager.getLock @doc_id, (args...) =>
  48. @callback(args...)
  49. done()
  50. it "should call tryLock multiple times until free", ->
  51. (@LockManager.tryLock.callCount > 1).should.equal true
  52. it "should return the callback with the lock value", ->
  53. @callback.calledWith(null, @lockValue).should.equal true
  54. describe "when the lock times out", ->
  55. beforeEach (done) ->
  56. time = Date.now()
  57. @LockManager.MAX_LOCK_WAIT_TIME = 5
  58. @LockManager.tryLock = sinon.stub().callsArgWith(1, null, false)
  59. @LockManager.getLock @doc_id, (args...) =>
  60. @callback(args...)
  61. done()
  62. it "should return the callback with an error", ->
  63. e = new Error("Timeout")
  64. e.doc_id = @doc_id
  65. @callback.calledWith(e).should.equal true