getLockTests.coffee 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. @callback = sinon.stub()
  15. @doc_id = "doc-id-123"
  16. describe "when the lock is not set", ->
  17. beforeEach (done) ->
  18. @lockValue = "mock-lock-value"
  19. @LockManager.tryLock = sinon.stub().callsArgWith(1, null, true, @lockValue)
  20. @LockManager.getLock @doc_id, (args...) =>
  21. @callback(args...)
  22. done()
  23. it "should try to get the lock", ->
  24. @LockManager.tryLock
  25. .calledWith(@doc_id)
  26. .should.equal true
  27. it "should only need to try once", ->
  28. @LockManager.tryLock.callCount.should.equal 1
  29. it "should return the callback with the lock value", ->
  30. @callback.calledWith(null, @lockValue).should.equal true
  31. describe "when the lock is initially set", ->
  32. beforeEach (done) ->
  33. @lockValue = "mock-lock-value"
  34. startTime = Date.now()
  35. tries = 0
  36. @LockManager.LOCK_TEST_INTERVAL = 5
  37. @LockManager.tryLock = (doc_id, callback = (error, isFree) ->) =>
  38. if (Date.now() - startTime < 20) or (tries < 2)
  39. tries = tries + 1
  40. callback null, false
  41. else
  42. callback null, true, @lockValue
  43. sinon.spy @LockManager, "tryLock"
  44. @LockManager.getLock @doc_id, (args...) =>
  45. @callback(args...)
  46. done()
  47. it "should call tryLock multiple times until free", ->
  48. (@LockManager.tryLock.callCount > 1).should.equal true
  49. it "should return the callback with the lock value", ->
  50. @callback.calledWith(null, @lockValue).should.equal true
  51. describe "when the lock times out", ->
  52. beforeEach (done) ->
  53. time = Date.now()
  54. @LockManager.MAX_LOCK_WAIT_TIME = 5
  55. @LockManager.tryLock = sinon.stub().callsArgWith(1, null, false)
  56. @LockManager.getLock @doc_id, (args...) =>
  57. @callback(args...)
  58. done()
  59. it "should return the callback with an error", ->
  60. e = new Error("Timeout")
  61. e.doc_id = @doc_id
  62. @callback.calledWith(e).should.equal true