summaryrefslogtreecommitdiffstats
path: root/toolkit/components/places/tests/unit/test_sql_guid_functions.js
blob: b4fbdac61228c24cd837330f8856d1b276a28009 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

/**
 * This file tests that the guid function generates a guid of the proper length,
 * with no invalid characters.
 */

/**
 * Checks all our invariants about our guids for a given result.
 *
 * @param aGuid
 *        The guid to check.
 */
function check_invariants(aGuid) {
  info("Checking guid '" + aGuid + "'");

  do_check_valid_places_guid(aGuid);
}

// Test Functions

function test_guid_invariants() {
  const kExpectedChars = 64;
  const kAllowedChars =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
  Assert.equal(kAllowedChars.length, kExpectedChars);
  const kGuidLength = 12;

  let checkedChars = [];
  for (let i = 0; i < kGuidLength; i++) {
    checkedChars[i] = {};
    for (let j = 0; j < kAllowedChars; j++) {
      checkedChars[i][kAllowedChars[j]] = false;
    }
  }

  // We run this until we've seen every character that we expect to see in every
  // position.
  let seenChars = 0;
  let stmt = DBConn().createStatement("SELECT GENERATE_GUID()");
  while (seenChars != kExpectedChars * kGuidLength) {
    Assert.ok(stmt.executeStep());
    let guid = stmt.getString(0);
    check_invariants(guid);

    for (let i = 0; i < guid.length; i++) {
      let character = guid[i];
      if (!checkedChars[i][character]) {
        checkedChars[i][character] = true;
        seenChars++;
      }
    }
    stmt.reset();
  }
  stmt.finalize();

  // One last reality check - make sure all of our characters were seen.
  for (let i = 0; i < kGuidLength; i++) {
    for (let j = 0; j < kAllowedChars; j++) {
      Assert.ok(checkedChars[i][kAllowedChars[j]]);
    }
  }

  run_next_test();
}

function test_guid_on_background() {
  // We should not assert if we execute this asynchronously.
  let stmt = DBConn().createAsyncStatement("SELECT GENERATE_GUID()");
  let checked = false;
  stmt.executeAsync({
    handleResult(aResult) {
      try {
        let row = aResult.getNextRow();
        check_invariants(row.getResultByIndex(0));
        Assert.equal(aResult.getNextRow(), null);
        checked = true;
      } catch (e) {
        do_throw(e);
      }
    },
    handleCompletion(aReason) {
      Assert.equal(aReason, Ci.mozIStorageStatementCallback.REASON_FINISHED);
      Assert.ok(checked);
      run_next_test();
    },
  });
  stmt.finalize();
}

// Test Runner

[test_guid_invariants, test_guid_on_background].forEach(fn => add_test(fn));