getLockTests.coffee 2.0 KB

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