getLockTests.coffee 2.2 KB

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