summaryrefslogtreecommitdiffstats
path: root/services/sync/tests/unit/test_utils_lock.js
blob: d1830787e63a32d88b67dcee88a52edd1f5a33a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
_("Make sure lock prevents calling with a shared lock");
Cu.import("resource://services-sync/util.js");

// Utility that we only use here.

function do_check_begins(thing, startsWith) {
  if (!(thing && thing.indexOf && (thing.indexOf(startsWith) == 0)))
    do_throw(thing + " doesn't begin with " + startsWith);
}

function run_test() {
  let ret, rightThis, didCall;
  let state, lockState, lockedState, unlockState;
  let obj = {
    _lock: Utils.lock,
    lock: function() {
      lockState = ++state;
      if (this._locked) {
        lockedState = ++state;
        return false;
      }
      this._locked = true;
      return true;
    },
    unlock: function() {
      unlockState = ++state;
      this._locked = false;
    },

    func: function() {
      return this._lock("Test utils lock",
                        function() {
                          rightThis = this == obj;
                          didCall = true;
                          return 5;
                        })();
    },

    throwy: function() {
      return this._lock("Test utils lock throwy",
                        function() {
                          rightThis = this == obj;
                          didCall = true;
                          this.throwy();
                        })();
    }
  };

  _("Make sure a normal call will call and return");
  rightThis = didCall = false;
  state = 0;
  ret = obj.func();
  do_check_eq(ret, 5);
  do_check_true(rightThis);
  do_check_true(didCall);
  do_check_eq(lockState, 1);
  do_check_eq(unlockState, 2);
  do_check_eq(state, 2);

  _("Make sure code that calls locked code throws");
  ret = null;
  rightThis = didCall = false;
  try {
    ret = obj.throwy();
    do_throw("throwy internal call should have thrown!");
  }
  catch(ex) {
    // Should throw an Error, not a string.
    do_check_begins(ex, "Could not acquire lock");
  }
  do_check_eq(ret, null);
  do_check_true(rightThis);
  do_check_true(didCall);
  _("Lock should be called twice so state 3 is skipped");
  do_check_eq(lockState, 4);
  do_check_eq(lockedState, 5);
  do_check_eq(unlockState, 6);
  do_check_eq(state, 6);
}