summaryrefslogtreecommitdiffstats
path: root/dom/localstorage/test/unit/head.js
blob: cd84f141643aee99cc361ffa9bbaa83bb4a2ea6e (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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/**
 * Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

// Tests are expected to define testSteps.
/* globals testSteps */

const NS_ERROR_DOM_QUOTA_EXCEEDED_ERR = 22;

function is(a, b, msg) {
  Assert.equal(a, b, msg);
}

function ok(cond, msg) {
  Assert.ok(!!cond, msg);
}

add_setup(function () {
  do_get_profile();

  enableTesting();

  registerCleanupFunction(resetTesting);
});

function returnToEventLoop() {
  return new Promise(function (resolve) {
    executeSoon(resolve);
  });
}

function enableTesting() {
  Services.prefs.setBoolPref("dom.simpleDB.enabled", true);
  Services.prefs.setBoolPref("dom.storage.testing", true);

  // xpcshell globals don't have associated clients in the Clients API sense, so
  // we need to disable client validation so that the unit tests are allowed to
  // use LocalStorage.
  Services.prefs.setBoolPref("dom.storage.client_validation", false);

  Services.prefs.setBoolPref("dom.quotaManager.testing", true);
}

function resetTesting() {
  Services.prefs.clearUserPref("dom.quotaManager.testing");
  Services.prefs.clearUserPref("dom.storage.client_validation");
  Services.prefs.clearUserPref("dom.storage.testing");
  Services.prefs.clearUserPref("dom.simpleDB.enabled");
}

function setGlobalLimit(globalLimit) {
  Services.prefs.setIntPref(
    "dom.quotaManager.temporaryStorage.fixedLimit",
    globalLimit
  );
}

function resetGlobalLimit() {
  Services.prefs.clearUserPref("dom.quotaManager.temporaryStorage.fixedLimit");
}

function setOriginLimit(originLimit) {
  Services.prefs.setIntPref("dom.storage.default_quota", originLimit);
}

function resetOriginLimit() {
  Services.prefs.clearUserPref("dom.storage.default_quota");
}

function setTimeout(callback, timeout) {
  let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);

  timer.initWithCallback(
    {
      notify() {
        callback();
      },
    },
    timeout,
    Ci.nsITimer.TYPE_ONE_SHOT
  );

  return timer;
}

function initStorage() {
  return Services.qms.init();
}

function initTemporaryStorage() {
  return Services.qms.initTemporaryStorage();
}

function initPersistentOrigin(principal) {
  return Services.qms.initializePersistentOrigin(principal);
}

function initTemporaryOrigin(persistence, principal) {
  return Services.qms.initializeTemporaryOrigin(persistence, principal);
}

function getOriginUsage(principal, fromMemory = false) {
  let request = Services.qms.getUsageForPrincipal(
    principal,
    function () {},
    fromMemory
  );

  return request;
}

function clear() {
  let request = Services.qms.clear();

  return request;
}

function clearOriginsByPattern(pattern) {
  let request = Services.qms.clearStoragesForOriginAttributesPattern(pattern);

  return request;
}

function clearOriginsByPrefix(principal, persistence) {
  let request = Services.qms.clearStoragesForOriginPrefix(
    principal,
    persistence
  );

  return request;
}

function clearOrigin(principal, persistence) {
  let request = Services.qms.clearStoragesForPrincipal(principal, persistence);

  return request;
}

function reset() {
  let request = Services.qms.reset();

  return request;
}

function resetOrigin(principal) {
  let request = Services.qms.resetStoragesForPrincipal(
    principal,
    "default",
    "ls"
  );

  return request;
}

function installPackage(packageName) {
  let currentDir = Services.dirsvc.get("CurWorkD", Ci.nsIFile);

  let packageFile = currentDir.clone();
  packageFile.append(packageName + ".zip");

  let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(
    Ci.nsIZipReader
  );
  zipReader.open(packageFile);

  let entryNames = [];
  let entries = zipReader.findEntries(null);
  while (entries.hasMore()) {
    let entry = entries.getNext();
    entryNames.push(entry);
  }
  entryNames.sort();

  for (let entryName of entryNames) {
    let zipentry = zipReader.getEntry(entryName);

    let file = getRelativeFile(entryName);

    if (zipentry.isDirectory) {
      file.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8));
    } else {
      let istream = zipReader.getInputStream(entryName);

      var ostream = Cc[
        "@mozilla.org/network/file-output-stream;1"
      ].createInstance(Ci.nsIFileOutputStream);
      ostream.init(file, -1, parseInt("0644", 8), 0);

      let bostream = Cc[
        "@mozilla.org/network/buffered-output-stream;1"
      ].createInstance(Ci.nsIBufferedOutputStream);
      bostream.init(ostream, 32768);

      bostream.writeFrom(istream, istream.available());

      istream.close();
      bostream.close();
    }
  }

  zipReader.close();
}

function getProfileDir() {
  return Services.dirsvc.get("ProfD", Ci.nsIFile);
}

// Given a "/"-delimited path relative to the profile directory,
// return an nsIFile representing the path.  This does not test
// for the existence of the file or parent directories.
// It is safe even on Windows where the directory separator is not "/",
// but make sure you're not passing in a "\"-delimited path.
function getRelativeFile(relativePath) {
  let profileDir = getProfileDir();

  let file = profileDir.clone();
  relativePath.split("/").forEach(function (component) {
    file.append(component);
  });

  return file;
}

function repeatChar(count, ch) {
  if (count == 0) {
    return "";
  }

  let result = ch;
  let count2 = count / 2;

  // Double the input until it is long enough.
  while (result.length <= count2) {
    result += result;
  }

  // Use substring to hit the precise length target without using extra memory.
  return result + result.substring(0, count - result.length);
}

function getPrincipal(url, attrs) {
  let uri = Services.io.newURI(url);
  if (!attrs) {
    attrs = {};
  }
  return Services.scriptSecurityManager.createContentPrincipal(uri, attrs);
}

function getCurrentPrincipal() {
  return Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal);
}

function getDefaultPrincipal() {
  return getPrincipal("http://example.com");
}

function getSimpleDatabase(principal, persistence) {
  let connection = Cc["@mozilla.org/dom/sdb-connection;1"].createInstance(
    Ci.nsISDBConnection
  );

  if (!principal) {
    principal = getDefaultPrincipal();
  }

  connection.init(principal, persistence);

  return connection;
}

function getLocalStorage(principal) {
  if (!principal) {
    principal = getDefaultPrincipal();
  }

  return Services.domStorageManager.createStorage(
    null,
    principal,
    principal,
    ""
  );
}

class RequestError extends Error {
  constructor(resultCode, resultName) {
    super(`Request failed (code: ${resultCode}, name: ${resultName})`);
    this.name = "RequestError";
    this.resultCode = resultCode;
    this.resultName = resultName;
  }
}

async function requestFinished(request) {
  await new Promise(function (resolve) {
    request.callback = function () {
      resolve();
    };
  });

  if (request.resultCode !== Cr.NS_OK) {
    throw new RequestError(request.resultCode, request.resultName);
  }

  return request.result;
}

function loadSubscript(path) {
  let file = do_get_file(path, false);
  let uri = Services.io.newFileURI(file);
  Services.scriptloader.loadSubScript(uri.spec);
}

async function readUsageFromUsageFile(usageFile) {
  let file = await File.createFromNsIFile(usageFile);

  let buffer = await new Promise(resolve => {
    let reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsArrayBuffer(file);
  });

  // Manually getting the lower 32-bits because of the lack of support for
  // 64-bit values currently from DataView/JS (other than the BigInt support
  // that's currently behind a flag).
  let view = new DataView(buffer, 8, 4);
  return view.getUint32();
}