summaryrefslogtreecommitdiffstats
path: root/dom/tests/mochitest/ajax/offline/offlineTests.js
blob: f239cd574258e0cb0eea76e3d581dd7436eaaed1 (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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Utility functions for offline tests.
var Cc = SpecialPowers.Cc;
var Ci = SpecialPowers.Ci;
var Cu = SpecialPowers.Cu;
var LoadContextInfo = Cc["@mozilla.org/load-context-info-factory;1"].getService(Ci.nsILoadContextInfoFactory);
var CommonUtils = Cu.import("resource://services-common/utils.js", {}).CommonUtils;

const kNetBase = 2152398848; // 0x804B0000
var NS_ERROR_CACHE_KEY_NOT_FOUND = kNetBase + 61;
var NS_ERROR_CACHE_KEY_WAIT_FOR_VALIDATION = kNetBase + 64;

// Reading the contents of multiple cache entries asynchronously
function OfflineCacheContents(urls) {
  this.urls = urls;
  this.contents = {};
}

OfflineCacheContents.prototype = {
QueryInterface: function(iid) {
    if (!iid.equals(Ci.nsISupports) &&
        !iid.equals(Ci.nsICacheEntryOpenCallback)) {
      throw Cr.NS_ERROR_NO_INTERFACE;
    }
    return this;
  },
onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
onCacheEntryAvailable: function(desc, isnew, applicationCache, status) {
    if (!desc) {
      this.fetch(this.callback);
      return;
    }

    var stream = desc.openInputStream(0);
    var sstream = Cc["@mozilla.org/scriptableinputstream;1"]
                 .createInstance(SpecialPowers.Ci.nsIScriptableInputStream);
    sstream.init(stream);
    this.contents[desc.key] = sstream.read(sstream.available());
    sstream.close();
    desc.close();
    this.fetch(this.callback);
  },

fetch: function(callback)
{
  this.callback = callback;
  if (this.urls.length == 0) {
    callback(this.contents);
    return;
  }

  var url = this.urls.shift();
  var self = this;

  var cacheStorage = OfflineTest.getActiveStorage();
  cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY, this);
}
};

var OfflineTest = {

_allowedByDefault: false,

_hasSlave: false,

// The window where test results should be sent.
_masterWindow: null,

// Array of all PUT overrides on the server
_pathOverrides: [],

// SJSs whom state was changed to be reverted on teardown
_SJSsStated: [],

setupChild: function()
{
  if (this._allowedByDefault) {
    this._masterWindow = window;
    return true;
  }

  if (window.parent.OfflineTest._hasSlave) {
    return false;
  }

  this._masterWindow = window.top;

  return true;
},

/**
 * Setup the tests.  This will reload the current page in a new window
 * if necessary.
 *
 * @return boolean Whether this window is the slave window
 *                 to actually run the test in.
 */
setup: function()
{
  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

  try {
    this._allowedByDefault = SpecialPowers.getBoolPref("offline-apps.allow_by_default");
  } catch (e) {}

  if (this._allowedByDefault) {
    this._masterWindow = window;

    return true;
  }

  if (!window.opener || !window.opener.OfflineTest ||
      !window.opener.OfflineTest._hasSlave) {
    // Offline applications must be toplevel windows and have the
    // offline-app permission.  Because we were loaded without the
    // offline-app permission and (probably) in an iframe, we need to
    // enable the pref and spawn a new window to perform the actual
    // tests.  It will use this window to report successes and
    // failures.

    if (SpecialPowers.testPermission("offline-app", Ci.nsIPermissionManager.ALLOW_ACTION, document)) {
      ok(false, "Previous test failed to clear offline-app permission!  Expect failures.");
    }
    SpecialPowers.addPermission("offline-app", Ci.nsIPermissionManager.ALLOW_ACTION, document);

    // Tests must run as toplevel windows.  Open a slave window to run
    // the test.
    this._hasSlave = true;
    window.open(window.location, "offlinetest");

    return false;
  }

  this._masterWindow = window.opener;

  return true;
},

teardownAndFinish: function()
{
  this.teardown(function(self) { self.finish(); });
},

teardown: function(callback)
{
  // First wait for any pending scheduled updates to finish
  this.waitForUpdates(function(self) {
    // Remove the offline-app permission we gave ourselves.

    SpecialPowers.removePermission("offline-app", window.document);

    // Clear all overrides on the server
    for (override in self._pathOverrides)
      self.deleteData(self._pathOverrides[override]);
    for (statedSJS in self._SJSsStated)
      self.setSJSState(self._SJSsStated[statedSJS], "");

    self.clear();
    callback(self);
  });
},

finish: function()
{
  if (this._allowedByDefault) {
    SimpleTest.executeSoon(SimpleTest.finish);
  } else if (this._masterWindow) {
    // Slave window: pass control back to master window, close itself.
    this._masterWindow.SimpleTest.executeSoon(this._masterWindow.OfflineTest.finish);
    window.close();
  } else {
    // Master window: finish test.
    SimpleTest.finish();
  }
},

//
// Mochitest wrappers - These forward tests to the proper mochitest window.
//
ok: function(condition, name, diag)
{
  return this._masterWindow.SimpleTest.ok(condition, name, diag);
},

is: function(a, b, name)
{
  return this._masterWindow.SimpleTest.is(a, b, name);
},

isnot: function(a, b, name)
{
  return this._masterWindow.SimpleTest.isnot(a, b, name);
},

todo: function(a, name)
{
  return this._masterWindow.SimpleTest.todo(a, name);
},

clear: function()
{
  // XXX: maybe we should just wipe out the entire disk cache.
  var applicationCache = this.getActiveCache();
  if (applicationCache) {
    applicationCache.discard();
  }
},

waitForUpdates: function(callback)
{
  var self = this;
  var observer = {
    notified: false,
    observe: function(subject, topic, data) {
      if (subject) {
        subject.QueryInterface(SpecialPowers.Ci.nsIOfflineCacheUpdate);
        dump("Update of " + subject.manifestURI.spec + " finished\n");
      }

      SimpleTest.executeSoon(function() {
        if (observer.notified) {
          return;
        }

        var updateservice = Cc["@mozilla.org/offlinecacheupdate-service;1"]
                            .getService(SpecialPowers.Ci.nsIOfflineCacheUpdateService);
        var updatesPending = updateservice.numUpdates;
        if (updatesPending == 0) {
          try {
            SpecialPowers.removeObserver(observer, "offline-cache-update-completed");
          } catch(ex) {}
          dump("All pending updates done\n");
          observer.notified = true;
          callback(self);
          return;
        }

        dump("Waiting for " + updateservice.numUpdates + " update(s) to finish\n");
      });
    }
  }

  SpecialPowers.addObserver(observer, "offline-cache-update-completed", false);

  // Call now to check whether there are some updates scheduled
  observer.observe();
},

failEvent: function(e)
{
  OfflineTest.ok(false, "Unexpected event: " + e.type);
},

// The offline API as specified has no way to watch the load of a resource
// added with applicationCache.mozAdd().
waitForAdd: function(url, onFinished) {
  // Check every half second for ten seconds.
  var numChecks = 20;

  var waitForAddListener = {
    onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
    onCacheEntryAvailable: function(entry, isnew, applicationCache, status) {
      if (entry) {
        entry.close();
        onFinished();
        return;
      }

      if (--numChecks == 0) {
        onFinished();
        return;
      }

      setTimeout(OfflineTest.priv(waitFunc), 500);
    }
  };

  var waitFunc = function() {
    var cacheStorage = OfflineTest.getActiveStorage();
    cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY, waitForAddListener);
  }

  setTimeout(this.priv(waitFunc), 500);
},

manifestURL: function(overload)
{
  var manifestURLspec;
  if (overload) {
    manifestURLspec = overload;
  } else {
    var win = window;
    while (win && !win.document.documentElement.getAttribute("manifest")) {
      if (win == win.parent)
        break;
      win = win.parent;
    }
    if (win)
      manifestURLspec = win.document.documentElement.getAttribute("manifest");
  }

  var ios = Cc["@mozilla.org/network/io-service;1"]
            .getService(Ci.nsIIOService)

  var baseURI = ios.newURI(window.location.href, null, null);
  return ios.newURI(manifestURLspec, null, baseURI);
},

loadContext: function()
{
  return SpecialPowers.wrap(window).QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
                                   .getInterface(SpecialPowers.Ci.nsIWebNavigation)
                                   .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
                                   .getInterface(SpecialPowers.Ci.nsILoadContext);
},

loadContextInfo: function()
{
  return LoadContextInfo.fromLoadContext(this.loadContext(), false);
},

getActiveCache: function(overload)
{
  // Note that this is the current active cache in the cache stack, not the
  // one associated with this window.
  var serv = Cc["@mozilla.org/network/application-cache-service;1"]
             .getService(Ci.nsIApplicationCacheService);
  var groupID = serv.buildGroupIDForInfo(this.manifestURL(overload), this.loadContextInfo());
  return serv.getActiveCache(groupID);
},

getActiveStorage: function()
{
  var cache = this.getActiveCache();
  if (!cache) {
    return null;
  }

  var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
                     .getService(Ci.nsICacheStorageService);
  return cacheService.appCacheStorage(LoadContextInfo.default, cache);
},

priv: function(func)
{
  var self = this;
  return function() {
    func(arguments);
  }
},

checkCacheEntries: function(entries, callback)
{
  var checkNextEntry = function() {
    if (entries.length == 0) {
      setTimeout(OfflineTest.priv(callback), 0);
    } else {
      OfflineTest.checkCache(entries[0][0], entries[0][1], checkNextEntry);
      entries.shift();
    }
  }

  checkNextEntry();
},

checkCache: function(url, expectEntry, callback)
{
  var cacheStorage = this.getActiveStorage();
  this._checkCache(cacheStorage, url, expectEntry, callback);
},

_checkCache: function(cacheStorage, url, expectEntry, callback)
{
  if (!cacheStorage) {
    if (expectEntry) {
      this.ok(false, url + " should exist in the offline cache (no session)");
    } else {
      this.ok(true, url + " should not exist in the offline cache (no session)");
    }
    if (callback) setTimeout(this.priv(callback), 0);
    return;
  }

  var _checkCacheListener = {
    onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
    onCacheEntryAvailable: function(entry, isnew, applicationCache, status) {
      if (entry) {
        if (expectEntry) {
          OfflineTest.ok(true, url + " should exist in the offline cache");
        } else {
          OfflineTest.ok(false, url + " should not exist in the offline cache");
        }
        entry.close();
      } else {
        if (status == NS_ERROR_CACHE_KEY_NOT_FOUND) {
          if (expectEntry) {
            OfflineTest.ok(false, url + " should exist in the offline cache");
          } else {
            OfflineTest.ok(true, url + " should not exist in the offline cache");
          }
        } else if (status == NS_ERROR_CACHE_KEY_WAIT_FOR_VALIDATION) {
          // There was a cache key that we couldn't access yet, that's good enough.
          if (expectEntry) {
            OfflineTest.ok(!mustBeValid, url + " should exist in the offline cache");
          } else {
            OfflineTest.ok(mustBeValid, url + " should not exist in the offline cache");
          }
        } else {
          OfflineTest.ok(false, "got invalid error for " + url);
        }
      }
      if (callback) setTimeout(OfflineTest.priv(callback), 0);
    }
  };

  cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY, _checkCacheListener);
},

setSJSState: function(sjsPath, stateQuery)
{
  var client = new XMLHttpRequest();
  client.open("GET", sjsPath + "?state=" + stateQuery, false);

  var appcachechannel = SpecialPowers.wrap(client).channel.QueryInterface(Ci.nsIApplicationCacheChannel);
  appcachechannel.chooseApplicationCache = false;
  appcachechannel.inheritApplicationCache = false;
  appcachechannel.applicationCache = null;

  client.send();

  if (stateQuery == "")
    delete this._SJSsStated[sjsPath];
  else
    this._SJSsStated.push(sjsPath);
}

};