getLockTests.coffee 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. sinon = require('sinon')
  2. chai = require('chai')
  3. should = chai.should()
  4. path = require('path')
  5. modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
  6. SandboxedModule = require('sandboxed-module')
  7. describe 'LockManager - getting the lock', ->
  8. beforeEach ->
  9. @LockManager = SandboxedModule.require modulePath, requires:
  10. "logger-sharelatex": log:->
  11. "redis-sharelatex":
  12. createClient : () =>
  13. auth:->
  14. "settings-sharelatex":{redis:{}}
  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. @LockManager.tryLock = sinon.stub().callsArgWith(1, null, true)
  21. @LockManager.getLock @doc_id, (args...) =>
  22. @callback(args...)
  23. done()
  24. it "should try to get the lock", ->
  25. @LockManager.tryLock
  26. .calledWith(@doc_id)
  27. .should.equal true
  28. it "should only need to try once", ->
  29. @LockManager.tryLock.callCount.should.equal 1
  30. it "should return the callback", ->
  31. @callback.calledWith(null).should.equal true
  32. describe "when the lock is initially set", ->
  33. beforeEach (done) ->
  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
  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", ->
  50. @callback.calledWith(null).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. @callback.calledWith(new Error("timeout")).should.equal true