getLockTests.coffee 2.0 KB

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