import FIREFOX_52_6_0esr_RELEASE from mozilla-esr52 hg repo

This commit is contained in:
Roy Tam 2018-01-19 03:59:58 +08:00
commit dcd9973243
150858 changed files with 23884658 additions and 0 deletions

1
dom/cache/test/mochitest/browser.ini vendored Normal file
View file

@ -0,0 +1 @@
[browser_cache_pb_window.js]

View file

@ -0,0 +1,81 @@
var name = 'pb-window-cache';
function testMatch(win) {
return new Promise(function(resolve, reject) {
win.caches.match('http://foo.com').then(function(response) {
ok(false, 'caches.match() should not return success');
reject();
}).catch(function(err) {
is('SecurityError', err.name, 'caches.match() should throw SecurityError');
resolve();
});
});
}
function testHas(win) {
return new Promise(function(resolve, reject) {
win.caches.has(name).then(function(result) {
ok(false, 'caches.has() should not return success');
reject();
}).catch(function(err) {
is('SecurityError', err.name, 'caches.has() should throw SecurityError');
resolve();
});
});
}
function testOpen(win) {
return new Promise(function(resolve, reject) {
win.caches.open(name).then(function(c) {
ok(false, 'caches.open() should not return success');
reject();
}).catch(function(err) {
is('SecurityError', err.name, 'caches.open() should throw SecurityError');
resolve();
});
});
}
function testDelete(win) {
return new Promise(function(resolve, reject) {
win.caches.delete(name).then(function(result) {
ok(false, 'caches.delete() should not return success');
reject();
}).catch(function(err) {
is('SecurityError', err.name, 'caches.delete() should throw SecurityError');
resolve();
});
});
}
function testKeys(win) {
return new Promise(function(resolve, reject) {
win.caches.keys().then(function(names) {
ok(false, 'caches.keys() should not return success');
reject();
}).catch(function(err) {
is('SecurityError', err.name, 'caches.keys() should throw SecurityError');
resolve();
});
});
}
function test() {
waitForExplicitFinish();
SpecialPowers.pushPrefEnv({'set': [['dom.caches.enabled', true],
['dom.caches.testing.enabled', true]]},
function() {
var privateWin = OpenBrowserWindow({private: true});
privateWin.addEventListener('load', function() {
Promise.all([
testMatch(privateWin),
testHas(privateWin),
testOpen(privateWin),
testDelete(privateWin),
testKeys(privateWin)
]).then(function() {
BrowserTestUtils.closeWindow(privateWin).then(finish);
});
});
});
}

0
dom/cache/test/mochitest/chrome.ini vendored Normal file
View file

132
dom/cache/test/mochitest/driver.js vendored Normal file
View file

@ -0,0 +1,132 @@
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// This helper script exposes a runTests function that takes the name of a
// test script as its input argument and runs the test in three different
// contexts:
// 1. Regular Worker context
// 2. Service Worker context
// 3. Window context
// The function returns a promise which will get resolved once all tests
// finish. The testFile argument is the name of the test file to be run
// in the different contexts, and the optional order argument can be set
// to either "parallel" or "sequential" depending on how the caller wants
// the tests to be run. If this argument is not provided, the default is
// "both", which runs the tests in both modes.
// The caller of this function is responsible to call SimpleTest.finish
// when the returned promise is resolved.
function runTests(testFile, order) {
function setupPrefs() {
return new Promise(function(resolve, reject) {
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.caches.testing.enabled", true],
["dom.serviceWorkers.enabled", true],
["dom.serviceWorkers.testing.enabled", true],
["dom.serviceWorkers.exemptFromPerDomainMax", true]]
}, function() {
resolve();
});
});
}
// adapted from dom/indexedDB/test/helpers.js
function clearStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var request = qms.clearStoragesForPrincipal(principal);
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function loadScript(script) {
return new Promise(function(resolve, reject) {
var s = document.createElement("script");
s.src = script;
s.onerror = reject;
s.onload = resolve;
document.body.appendChild(s);
});
}
function importDrivers() {
return Promise.all([loadScript("worker_driver.js"),
loadScript("serviceworker_driver.js")]);
}
function runWorkerTest() {
return workerTestExec(testFile);
}
function runServiceWorkerTest() {
return serviceWorkerTestExec(testFile);
}
function runFrameTest() {
return new Promise(function(resolve, reject) {
var iframe = document.createElement("iframe");
iframe.src = "frame.html";
iframe.onload = function() {
var doc = iframe.contentDocument;
var s = doc.createElement("script");
s.src = testFile;
window.addEventListener("message", function onMessage(event) {
if (event.data.context != "Window") {
return;
}
if (event.data.type == 'finish') {
window.removeEventListener("message", onMessage);
resolve();
} else if (event.data.type == 'status') {
ok(event.data.status, event.data.context + ": " + event.data.msg);
}
}, false);
doc.body.appendChild(s);
};
document.body.appendChild(iframe);
});
}
SimpleTest.waitForExplicitFinish();
if (typeof order == "undefined") {
order = "sequential"; // sequential by default, see bug 1143222.
// TODO: Make this "both" again.
}
ok(order == "parallel" || order == "sequential" || order == "both",
"order argument should be valid");
if (order == "both") {
info("Running tests in both modes; first: sequential");
return runTests(testFile, "sequential")
.then(function() {
info("Running tests in parallel mode");
return runTests(testFile, "parallel");
});
}
if (order == "sequential") {
return setupPrefs()
.then(importDrivers)
.then(runWorkerTest)
.then(clearStorage)
.then(runServiceWorkerTest)
.then(clearStorage)
.then(runFrameTest)
.then(clearStorage)
.catch(function(e) {
ok(false, "A promise was rejected during test execution: " + e);
});
}
return setupPrefs()
.then(importDrivers)
.then(() => Promise.all([runWorkerTest(), runServiceWorkerTest(), runFrameTest()]))
.then(clearStorage)
.catch(function(e) {
ok(false, "A promise was rejected during test execution: " + e);
});
}

2
dom/cache/test/mochitest/empty.html vendored Normal file
View file

@ -0,0 +1,2 @@
<!DOCTYPE html>
<!-- This is only used to give us access to the caches global after setting the pref. -->

17
dom/cache/test/mochitest/frame.html vendored Normal file
View file

@ -0,0 +1,17 @@
<!DOCTYPE html>
<script>
var context = "Window";
function ok(a, msg) {
parent.postMessage({type: 'status', status: !!a,
msg: a + ": " + msg, context: context}, "*");
}
function is(a, b, msg) {
parent.postMessage({type: 'status', status: a === b,
msg: a + " === " + b + ": " + msg, context: context}, "*");
}
function testDone() {
parent.postMessage({type: 'finish', context: context}, "*");
}
</script>

1002
dom/cache/test/mochitest/large_url_list.js vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,6 @@
<!DOCTYPE html>
<script>
navigator.serviceWorker.onmessage = function(e) {
window.parent.postMessage(e.data, "*");
};
</script>

5
dom/cache/test/mochitest/mirror.sjs vendored Normal file
View file

@ -0,0 +1,5 @@
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200, "OK");
response.setHeader("Mirrored", request.getHeader("Mirror"));
response.write(request.getHeader("Mirror"));
}

47
dom/cache/test/mochitest/mochitest.ini vendored Normal file
View file

@ -0,0 +1,47 @@
[DEFAULT]
support-files =
test_cache.js
test_cache_add.js
worker_driver.js
worker_wrapper.js
frame.html
message_receiver.html
driver.js
serviceworker_driver.js
test_cache_match_request.js
test_cache_matchAll_request.js
test_cache_overwrite.js
mirror.sjs
test_cache_match_vary.js
vary.sjs
test_caches.js
test_cache_keys.js
test_cache_put.js
test_cache_requestCache.js
test_cache_delete.js
test_cache_put_reorder.js
test_cache_redirect.js
test_cache_https.js
large_url_list.js
empty.html
[test_cache.html]
[test_cache_add.html]
[test_cache_match_request.html]
[test_cache_matchAll_request.html]
[test_cache_overwrite.html]
[test_cache_match_vary.html]
[test_caches.html]
[test_cache_keys.html]
[test_cache_put.html]
[test_cache_requestCache.html]
[test_cache_delete.html]
[test_cache_put_reorder.html]
[test_cache_https.html]
[test_cache_redirect.html]
[test_cache_restart.html]
[test_cache_shrink.html]
[test_cache_orphaned_cache.html]
[test_cache_orphaned_body.html]
[test_cache_untrusted.html]
[test_chrome_constructor.html]

View file

@ -0,0 +1,44 @@
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
function serviceWorkerTestExec(testFile) {
var isB2G = !navigator.userAgent.includes("Android") &&
/Mobile|Tablet/.test(navigator.userAgent);
if (isB2G) {
// TODO B2G doesn't support running service workers for now due to bug 1137683.
dump("Skipping running the test in SW until bug 1137683 gets fixed.\n");
return Promise.resolve();
}
return new Promise(function(resolve, reject) {
function setupSW(registration) {
var worker = registration.waiting ||
registration.active;
window.addEventListener("message",function onMessage(event) {
if (event.data.context != "ServiceWorker") {
return;
}
if (event.data.type == 'finish') {
window.removeEventListener("message", onMessage);
registration.unregister()
.then(resolve)
.catch(reject);
} else if (event.data.type == 'status') {
ok(event.data.status, event.data.context + ": " + event.data.msg);
}
}, false);
worker.onerror = reject;
var iframe = document.createElement("iframe");
iframe.src = "message_receiver.html";
iframe.onload = function() {
worker.postMessage({ script: testFile });
};
document.body.appendChild(iframe);
}
navigator.serviceWorker.ready.then(setupSW);
navigator.serviceWorker.register("worker_wrapper.js", {scope: "."});
});
}

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate Interfaces Exposed to Workers</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

131
dom/cache/test/mochitest/test_cache.js vendored Normal file
View file

@ -0,0 +1,131 @@
var c = null
var request = "http://example.com/hmm?q=foobar" + context;
var response = new Response("This is some Response!");
var name = 'snafu' + context;
var foobar = 'foobar' + context;
ok(!!caches, 'caches object should be available on global');
caches.open(name).then(function(openCache) {
ok(openCache instanceof Cache, 'cache object should be resolved from caches.open');
return caches.has(name);
}).then(function(hasResult) {
ok(hasResult, 'caches.has() should resolve true');
return caches.keys();
}).then(function(keys) {
ok(!!keys, 'caches.keys() should resolve to a truthy value');
ok(keys.length >= 1, 'caches.keys() should resolve to an array of length at least 1');
ok(keys.indexOf(name) >= 0, 'caches.keys() should resolve to an array containing key');
return caches.delete(name);
}).then(function(deleteResult) {
ok(deleteResult, 'caches.delete() should resolve true');
return caches.has(name);
}).then(function(hasMissingCache) {
ok(!hasMissingCache, 'missing key should return false from has');
}).then(function() {
return caches.open(name);
}).then(function(snafu) {
return snafu.keys();
}).then(function(empty) {
is(0, empty.length, 'cache.keys() should resolve to an array of length 0');
}).then(function() {
return caches.open(name);
}).then(function(snafu) {
var req = './cachekey';
var res = new Response("Hello world");
return snafu.put('ftp://invalid', res).then(function() {
ok(false, 'This should fail');
}).catch(function (err) {
is(err.name, 'TypeError', 'put() should throw TypeError for invalid scheme');
return snafu.put(req, res);
}).then(function(v) {
return snafu;
});
}).then(function(snafu) {
return Promise.all([snafu, snafu.keys()]);
}).then(function(args) {
var snafu = args[0];
var keys = args[1];
is(1, keys.length, 'cache.keys() should resolve to an array of length 1');
ok(keys[0] instanceof Request, 'key should be a Request');
ok(keys[0].url.match(/cachekey$/), 'Request URL should match original');
return Promise.all([snafu, snafu.match(keys[0]), snafu.match('ftp://invalid')]);
}).then(function(args) {
var snafu = args[0];
var response = args[1];
ok(response instanceof Response, 'value should be a Response');
is(response.status, 200, 'Response status should be 200');
is(undefined, args[2], 'Match with invalid scheme should resolve undefined');
return Promise.all([snafu, snafu.put('./cachekey2', response)]);
}).then(function(args) {
var snafu = args[0]
return snafu.match('./cachekey2');
}).then(function(response) {
return response.text().then(function(v) {
is(v, "Hello world", "Response body should match original");
});
}).then(function() {
// FIXME(nsm): Can't use a Request object for now since the operations
// consume it's 'body'. See
// https://github.com/slightlyoff/ServiceWorker/issues/510.
return caches.open(foobar);
}).then(function(openCache) {
c = openCache;
return c.put(request, response);
}).then(function(putResponse) {
is(putResponse, undefined, 'The promise should resolve to undefined');
return c.keys(request);
}).then(function(keys) {
ok(keys, 'Valid keys object expected');
is(keys.length, 1, 'Only one key is expected');
return c.keys();
}).then(function(keys) {
ok(keys, 'Valid keys object expected');
is(keys.length, 1, 'Only one key is expected');
return c.matchAll(request);
}).then(function(matchAllResponses) {
ok(matchAllResponses, 'matchAll should succeed');
is(matchAllResponses.length, 1, 'Only one match is expected');
return c.match(request);
}).then(function(matchResponse) {
ok(matchResponse, 'match should succeed');
return caches.match(request);
}).then(function(storageMatchResponse) {
ok(storageMatchResponse, 'storage match should succeed');
return caches.match(request, {cacheName:foobar});
}).then(function(storageMatchResponse) {
ok(storageMatchResponse, 'storage match with cacheName should succeed');
var request2 = new Request("http://example.com/hmm?q=snafu" + context);
return c.match(request2, {ignoreSearch:true});
}).then(function(match2Response) {
ok(match2Response, 'match should succeed');
return c.delete(request);
}).then(function(deleteResult) {
ok(deleteResult, 'delete should succeed');
return c.keys();
}).then(function(keys) {
ok(keys, 'Valid keys object expected');
is(keys.length, 0, 'Zero keys is expected');
return c.matchAll(request);
}).then(function(matchAll2Responses) {
ok(matchAll2Responses, 'matchAll should succeed');
is(matchAll2Responses.length, 0, 'Zero matches is expected');
return caches.has(foobar);
}).then(function(hasResult) {
ok(hasResult, 'has should succeed');
return caches.keys();
}).then(function(keys) {
ok(keys, 'Valid keys object expected');
ok(keys.length >= 2, 'At least two keys are expected');
ok(keys.indexOf(name) >= 0, 'snafu should exist');
ok(keys.indexOf(foobar) >= keys.indexOf(name), 'foobar should come after it');
return caches.delete(foobar);
}).then(function(deleteResult) {
ok(deleteResult, 'delete should succeed');
return caches.has(foobar);
}).then(function(hasMissingCache) {
ok(!hasMissingCache, 'has should have a result');
return caches.delete(name);
}).then(function(deleteResult) {
ok(deleteResult, 'delete should succeed');
testDone();
})

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate Interfaces Exposed to Workers</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_add.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,55 @@
var singleUrl = './test_cache_add.js';
var urlList = [
'./empty.html',
'./frame.html',
'./test_cache.js'
];
var cache;
var name = "adder" + context;
caches.open(name).then(function(openCache) {
cache = openCache;
return cache.add('ftp://example.com/invalid' + context);
}).catch(function (err) {
is(err.name, 'TypeError', 'add() should throw TypeError for invalid scheme');
return cache.addAll(['http://example.com/valid' + context, 'ftp://example.com/invalid' + context]);
}).catch(function (err) {
is(err.name, 'TypeError', 'addAll() should throw TypeError for invalid scheme');
var promiseList = urlList.map(function(url) {
return cache.match(url);
});
promiseList.push(cache.match(singleUrl));
return Promise.all(promiseList);
}).then(function(resultList) {
is(urlList.length + 1, resultList.length, 'Expected number of results');
resultList.every(function(result) {
is(undefined, result, 'URLs should not already be in the cache');
});
return cache.add(singleUrl);
}).then(function(result) {
is(undefined, result, 'Successful add() should resolve undefined');
return cache.addAll(urlList);
}).then(function(result) {
is(undefined, result, 'Successful addAll() should resolve undefined');
var promiseList = urlList.map(function(url) {
return cache.match(url);
});
promiseList.push(cache.match(singleUrl));
return Promise.all(promiseList);
}).then(function(resultList) {
is(urlList.length + 1, resultList.length, 'Expected number of results');
resultList.every(function(result) {
ok(!!result, 'Responses should now be in cache for each URL.');
});
return cache.matchAll();
}).then(function(resultList) {
is(urlList.length + 1, resultList.length, 'Expected number of results');
resultList.every(function(result) {
ok(!!result, 'Responses should now be in cache for each URL.');
});
return caches.delete(name);
}).then(function() {
testDone();
}).catch(function(err) {
ok(false, 'Caught error: ' + err);
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate the Cache.delete() method</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_delete.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,111 @@
var name = "delete" + context;
var c;
function setupTest(reqs) {
return new Promise(function(resolve, reject) {
var cache;
caches.open(name).then(function(c) {
cache = c;
return c.addAll(reqs);
}).then(function() {
resolve(cache);
}).catch(function(err) {
reject(err);
});
});
}
function testBasics() {
var tests = [
"//mochi.test:8888/?foo" + context,
"//mochi.test:8888/?bar" + context,
];
var cache;
return setupTest(tests)
.then(function(c) {
cache = c;
return cache.delete("//mochi.test:8888/?baz");
}).then(function(deleted) {
ok(!deleted, "Deleting a non-existing entry should fail");
return cache.keys();
}).then(function(keys) {
is(keys.length, 2, "No entries from the cache should be deleted");
return cache.delete(tests[0]);
}).then(function(deleted) {
ok(deleted, "Deleting an existing entry should succeed");
return cache.keys();
}).then(function(keys) {
is(keys.length, 1, "Only one entry should exist now");
ok(keys[0].url.indexOf(tests[1]) >= 0, "The correct entry must be deleted");
});
}
function testFragment() {
var tests = [
"//mochi.test:8888/?foo" + context,
"//mochi.test:8888/?bar" + context,
"//mochi.test:8888/?baz" + context + "#fragment",
];
var cache;
return setupTest(tests)
.then(function(c) {
cache = c;
return cache.delete(tests[0] + "#fragment");
}).then(function(deleted) {
ok(deleted, "Deleting an existing entry should succeed");
return cache.keys();
}).then(function(keys) {
is(keys.length, 2, "Only one entry should exist now");
ok(keys[0].url.indexOf(tests[1]) >= 0, "The correct entry must be deleted");
ok(keys[1].url.indexOf(tests[2].replace("#fragment", "")) >= 0, "The correct entry must be deleted");
// Now, delete a request that was added with a fragment
return cache.delete("//mochi.test:8888/?baz" + context);
}).then(function(deleted) {
ok(deleted, "Deleting an existing entry should succeed");
return cache.keys();
}).then(function(keys) {
is(keys.length, 1, "Only one entry should exist now");
ok(keys[0].url.indexOf(tests[1]) >= 0, "3The correct entry must be deleted");
});
}
function testInterleaved() {
var tests = [
"//mochi.test:8888/?foo" + context,
"//mochi.test:8888/?bar" + context,
];
var newURL = "//mochi.test:8888/?baz" + context;
var cache;
return setupTest(tests)
.then(function(c) {
cache = c;
// Simultaneously add and delete a request
return Promise.all([
cache.delete(newURL),
cache.add(newURL),
]);
}).then(function(result) {
ok(!result[1], "deletion should fail");
return cache.keys();
}).then(function(keys) {
is(keys.length, 3, "Tree entries should still exist");
ok(keys[0].url.indexOf(tests[0]) >= 0, "The correct entry must be deleted");
ok(keys[1].url.indexOf(tests[1]) >= 0, "The correct entry must be deleted");
ok(keys[2].url.indexOf(newURL) >= 0, "The new entry should be correctly inserted");
});
}
// Make sure to clean up after each test step.
function step(testPromise) {
return testPromise.then(function() {
caches.delete(name);
});
}
step(testBasics()).then(function() {
return step(testFragment());
}).then(function() {
return step(testInterleaved());
}).then(function() {
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate Interfaces Exposed to Workers</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_https.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,31 @@
var cache = null;
var name = 'https_' + context;
var urlBase = 'https://example.com/tests/dom/cache/test/mochitest';
var url1 = urlBase + '/test_cache.js';
var url2 = urlBase + '/test_cache_add.js';
function addOpaque(cache, url) {
return fetch(new Request(url, { mode: 'no-cors' })).then(function(response) {
return cache.put(url, response);
});
}
caches.open(name).then(function(c) {
cache = c;
return Promise.all([
addOpaque(cache, url1),
addOpaque(cache, url2)
]);
}).then(function() {
return cache.delete(url1);
}).then(function(result) {
ok(result, 'Cache entry should be deleted');
return cache.delete(url2);
}).then(function(result) {
ok(result, 'Cache entry should be deleted');
cache = null;
return caches.delete(name);
}).then(function(result) {
ok(result, 'Cache should be deleted');
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate the Cache.keys() method</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_keys.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,74 @@
var name = "keys" + context;
var c;
var tests = [
"//mochi.test:8888/?page" + context,
"//mochi.test:8888/?another" + context,
];
caches.open(name).then(function(cache) {
c = cache;
return c.addAll(tests);
}).then(function() {
// Add another cache entry using Cache.add
var another = "//mochi.test:8888/?yetanother" + context;
tests.push(another);
return c.add(another);
}).then(function() {
// Add another cache entry with URL fragment using Cache.add
var anotherWithFragment = "//mochi.test:8888/?fragment" + context + "#fragment";
tests.push(anotherWithFragment);
return c.add(anotherWithFragment);
}).then(function() {
return c.keys();
}).then(function(keys) {
is(keys.length, tests.length, "Same number of elements");
// Verify both the insertion order of the requests and their validity.
keys.forEach(function(r, i) {
ok(r instanceof Request, "Valid request object");
ok(r.url.indexOf(tests[i]) >= 0, "Valid URL");
});
// Try searching for just one request
return c.keys(tests[1]);
}).then(function(keys) {
is(keys.length, 1, "One match should be found");
ok(keys[0].url.indexOf(tests[1]) >= 0, "Valid URL");
// Try to see if ignoreSearch works as expected.
return c.keys(new Request("//mochi.test:8888/?foo"), {ignoreSearch: true});
}).then(function(keys) {
is(keys.length, tests.length, "Same number of elements");
keys.forEach(function(r, i) {
ok(r instanceof Request, "Valid request object");
ok(r.url.indexOf(tests[i]) >= 0, "Valid URL");
});
// Try to see if ignoreMethod works as expected
return Promise.all(
["POST", "PUT", "DELETE", "OPTIONS"]
.map(function(method) {
var req = new Request(tests[2], {method: method});
return c.keys(req)
.then(function(keys) {
is(keys.length, 0, "No request should be matched without ignoreMethod");
return c.keys(req, {ignoreMethod: true});
}).then(function(keys) {
is(keys.length, 1, "One match should be found");
ok(keys[0].url.indexOf(tests[2]) >= 0, "Valid URL");
});
})
);
}).then(function() {
// But HEAD should be allowed even without ignoreMethod
return c.keys(new Request(tests[0], {method: "HEAD"}));
}).then(function(keys) {
is(keys.length, 1, "One match should be found");
ok(keys[0].url.indexOf(tests[0]) >= 0, "Valid URL");
// Make sure cacheName is ignored.
return c.keys(tests[0], {cacheName: "non-existing-cache"});
}).then(function(keys) {
is(keys.length, 1, "One match should be found");
ok(keys[0].url.indexOf(tests[0]) >= 0, "Valid URL");
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The cache should be successfully deleted");
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate calling matchAll with a Request object</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_matchAll_request.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,183 @@
var request1 = new Request("//mochi.test:8888/?1&" + context + "#fragment");
var request2 = new Request("//mochi.test:8888/?2&" + context);
var request3 = new Request("//mochi.test:8888/?3&" + context);
var requestWithAltQS = new Request("//mochi.test:8888/?queryString");
var unknownRequest = new Request("//mochi.test:8888/non/existing/path?" + context);
var response1, response3;
var c;
var response1Text, response3Text;
var name = "matchAll-request" + context;
function checkResponse(r, response, responseText) {
ok(r !== response, "The objects should not be the same");
is(r.url, response.url.replace("#fragment", ""),
"The URLs should be the same");
is(r.status, response.status, "The status codes should be the same");
is(r.type, response.type, "The response types should be the same");
is(r.ok, response.ok, "Both responses should have succeeded");
is(r.statusText, response.statusText,
"Both responses should have the same status text");
return r.text().then(function(text) {
// Avoid dumping out the large response text to the log if they're equal.
if (text !== responseText) {
is(text, responseText, "The response body should be correct");
}
});
}
fetch(new Request(request1)).then(function(r) {
response1 = r;
return response1.text();
}).then(function(text) {
response1Text = text;
return fetch(new Request(request3));
}).then(function(r) {
response3 = r;
return response3.text();
}).then(function(text) {
response3Text = text;
return testRequest(request1, request2, request3, unknownRequest,
requestWithAltQS,
request1.url.replace("#fragment", "#other"));
}).then(function() {
return testRequest(request1.url, request2.url, request3.url,
unknownRequest.url, requestWithAltQS.url,
request1.url.replace("#fragment", "#other"));
}).then(function() {
testDone();
});
// The request arguments can either be a URL string, or a Request object.
function testRequest(request1, request2, request3, unknownRequest,
requestWithAlternateQueryString,
requestWithDifferentFragment) {
return caches.open(name).then(function(cache) {
c = cache;
return c.add(request1);
}).then(function() {
return c.add(request3);
}).then(function() {
return Promise.all(
["HEAD", "POST", "PUT", "DELETE", "OPTIONS"]
.map(function(method) {
var r = new Request(request1, {method: method});
return c.add(r)
.then(function() {
ok(false, "Promise should be rejected");
}, function(err) {
is(err.name, "TypeError", "Adding a request with type '" + method + "' should fail");
});
})
);
}).then(function() {
return c.matchAll(request1);
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, response1Text);
}).then(function() {
return c.matchAll(new Request(request1, {method: "HEAD"}));
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, "");
}).then(function() {
return c.matchAll(new Request(request1, {method: "HEAD"}), {ignoreMethod: true});
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, response1Text);
}).then(function() {
return Promise.all(
["POST", "PUT", "DELETE", "OPTIONS"]
.map(function(method) {
var req = new Request(request1, {method: method});
return c.matchAll(req)
.then(function(r) {
is(r.length, 0, "Searching for a request with a non-GET/HEAD method should not succeed");
return c.matchAll(req, {ignoreMethod: true});
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, response1Text);
});
})
);
}).then(function() {
return c.matchAll(requestWithDifferentFragment);
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, response1Text);
}).then(function() {
return c.matchAll(requestWithAlternateQueryString,
{ignoreSearch: true});
}).then(function(r) {
is(r.length, 2, "Should find 2 items");
return Promise.all([
checkResponse(r[0], response1, response1Text),
checkResponse(r[1], response3, response3Text)
]);
}).then(function() {
return c.matchAll(request3);
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response3, response3Text);
}).then(function() {
return c.matchAll();
}).then(function(r) {
is(r.length, 2, "Should find 2 items");
return Promise.all([
checkResponse(r[0], response1, response1Text),
checkResponse(r[1], response3, response3Text)
]);
}).then(function() {
return caches.match(request1, {cacheName: name + "mambojambo"})
.then(function() {
is(typeof r, "undefined", 'Searching in the wrong cache should resolve to undefined');
return caches.has(name + "mambojambo");
}).then(function(hasCache) {
ok(!hasCache, 'The wrong cache should still not exist');
});
}).then(function() {
return c.matchAll(unknownRequest);
}).then(function(r) {
is(r.length, 0, "Searching for an unknown request should not succeed");
return caches.match(unknownRequest, {cacheName: name});
}).then(function(r) {
is(typeof r, "undefined", "Searching for an unknown request should not succeed");
// Make sure that cacheName is ignored on Cache
return c.matchAll(request1, {cacheName: name + "mambojambo"});
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, response1Text);
}).then(function() {
return caches.delete(name);
}).then(function(success) {
ok(success, "We should be able to delete the cache successfully");
// Make sure that the cache is still usable after deletion.
return c.matchAll(request1);
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response1, response1Text);
}).then(function() {
return c.matchAll(request3);
}).then(function(r) {
is(r.length, 1, "Should only find 1 item");
return checkResponse(r[0], response3, response3Text);
}).then(function() {
return c.matchAll();
}).then(function(r) {
is(r.length, 2, "Should find 2 items");
return Promise.all([
checkResponse(r[0], response1, response1Text),
checkResponse(r[1], response3, response3Text)
]);
}).then(function() {
// Now, drop the cache, reopen and verify that we can't find the request any more.
c = null;
return caches.open(name);
}).then(function(cache) {
return cache.matchAll();
}).then(function(r) {
is(r.length, 0, "Searching in the cache after deletion should not succeed");
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The cache should be deleted successfully");
});
}

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate calling match with a Request object</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_match_request.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,145 @@
var request = new Request("//mochi.test:8888/?" + context + "#fragment");
var requestWithAltQS = new Request("//mochi.test:8888/?queryString");
var unknownRequest = new Request("//mochi.test:8888/non/existing/path?" + context);
var response;
var c;
var responseText;
var name = "match-request" + context;
function checkResponse(r, expectedBody) {
if (expectedBody === undefined) {
expectedBody = responseText;
}
ok(r !== response, "The objects should not be the same");
is(r.url, response.url.replace("#fragment", ""),
"The URLs should be the same");
is(r.status, response.status, "The status codes should be the same");
is(r.type, response.type, "The response types should be the same");
is(r.ok, response.ok, "Both responses should have succeeded");
is(r.statusText, response.statusText,
"Both responses should have the same status text");
return r.text().then(function(text) {
// Avoid dumping out the large response text to the log if they're equal.
if (text !== expectedBody) {
is(text, responseText, "The response body should be correct");
}
});
}
fetch(new Request(request)).then(function(r) {
response = r;
return response.text();
}).then(function(text) {
responseText = text;
return testRequest(request, unknownRequest, requestWithAltQS,
request.url.replace("#fragment", "#other"));
}).then(function() {
return testRequest(request.url, unknownRequest.url, requestWithAltQS.url,
request.url.replace("#fragment", "#other"));
}).then(function() {
testDone();
});
// The request argument can either be a URL string, or a Request object.
function testRequest(request, unknownRequest, requestWithAlternateQueryString,
requestWithDifferentFragment) {
return caches.open(name).then(function(cache) {
c = cache;
return c.add(request);
}).then(function() {
return Promise.all(
["HEAD", "POST", "PUT", "DELETE", "OPTIONS"]
.map(function(method) {
var r = new Request(request, {method: method});
return c.add(r)
.then(function() {
ok(false, "Promise should be rejected");
}, function(err) {
is(err.name, "TypeError", "Adding a request with type '" + method + "' should fail");
});
})
);
}).then(function() {
return c.match(request);
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return c.match(new Request(request, {method: "HEAD"}));
}).then(function(r) {
return checkResponse(r, '');
}).then(function() {
return c.match(new Request(request, {method: "HEAD"}), {ignoreMethod: true});
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return Promise.all(
["POST", "PUT", "DELETE", "OPTIONS"]
.map(function(method) {
var req = new Request(request, {method: method});
return c.match(req)
.then(function(r) {
is(typeof r, "undefined", "Searching for a request with a non-GET/HEAD method should not succeed");
return c.match(req, {ignoreMethod: true});
}).then(function(r) {
return checkResponse(r);
});
})
);
}).then(function() {
return caches.match(request);
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return caches.match(requestWithDifferentFragment);
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return caches.match(requestWithAlternateQueryString,
{ignoreSearch: true, cacheName: name});
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return caches.match(request, {cacheName: name});
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return caches.match(request, {cacheName: name + "mambojambo"})
.then(function(result) {
is(typeof r, "undefined", 'Searching in the wrong cache should resolve to undefined');
return caches.has(name + "mambojambo");
}).then(function(hasCache) {
ok(!hasCache, 'The wrong cache should still not exist');
});
}).then(function() {
// Make sure that cacheName is ignored on Cache
return c.match(request, {cacheName: name + "mambojambo"});
}).then(function(r) {
return checkResponse(r);
}).then(function() {
return c.match(unknownRequest);
}).then(function(r) {
is(typeof r, "undefined", "Searching for an unknown request should not succeed");
return caches.match(unknownRequest);
}).then(function(r) {
is(typeof r, "undefined", "Searching for an unknown request should not succeed");
return caches.match(unknownRequest, {cacheName: name});
}).then(function(r) {
is(typeof r, "undefined", "Searching for an unknown request should not succeed");
return caches.delete(name);
}).then(function(success) {
ok(success, "We should be able to delete the cache successfully");
// Make sure that the cache is still usable after deletion.
return c.match(request);
}).then(function(r) {
return checkResponse(r);
}).then(function() {
// Now, drop the cache, reopen and verify that we can't find the request any more.
c = null;
return caches.open(name);
}).then(function(cache) {
return cache.match(request);
}).then(function(r) {
is(typeof r, "undefined", "Searching in the cache after deletion should not succeed");
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The cache should be deleted successfully");
});
}

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate calling match with requests involving the Vary header</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_match_vary.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,334 @@
var requestURL = "//mochi.test:8888/tests/dom/cache/test/mochitest/vary.sjs?" + context;
var name = "match-vary" + context;
function checkResponse(r, response, responseText) {
ok(r !== response, "The objects should not be the same");
is(r.url, response.url.replace("#fragment", ""),
"The URLs should be the same");
is(r.status, response.status, "The status codes should be the same");
is(r.type, response.type, "The response types should be the same");
is(r.ok, response.ok, "Both responses should have succeeded");
is(r.statusText, response.statusText,
"Both responses should have the same status text");
is(r.headers.get("Vary"), response.headers.get("Vary"),
"Both responses should have the same Vary header");
return r.text().then(function(text) {
is(text, responseText, "The response body should be correct");
});
}
// Returns a Promise that will be resolved to an object with the following
// properties:
// * cache: A Cache object that contains one entry fetched with headers.
// * response: A Response object which is the result of fetching a request
// with the specified headers.
// * responseText: The body of the above response object.
function setupTest(headers) {
return setupTestMultipleEntries([headers]).then(function(test) {
return {response: test.response[0],
responseText: test.responseText[0],
cache: test.cache};
});
}
function setupTestMultipleEntries(headers) {
ok(Array.isArray(headers), "headers should be an array");
return new Promise(function(resolve, reject) {
var response, responseText, cache;
Promise.all(headers.map(function(h) {
return fetch(requestURL, {headers: h});
})).then(function(r) {
response = r;
return Promise.all(response.map(function(r) {
return r.text();
}));
}).then(function(text) {
responseText = text;
return caches.open(name);
}).then(function(c) {
cache = c;
return Promise.all(headers.map(function(h) {
return c.add(new Request(requestURL, {headers: h}));
}));
}).then(function() {
resolve({response: response, responseText: responseText, cache: cache});
}).catch(function(err) {
reject(err);
});
});
}
function testBasics() {
var test;
return setupTest({"WhatToVary": "Custom"})
.then(function(t) {
test = t;
// Ensure that searching without specifying a Custom header succeeds.
return test.cache.match(requestURL);
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
}).then(function() {
// Ensure that searching with a non-matching value for the Custom header fails.
return test.cache.match(new Request(requestURL, {headers: {"Custom": "foo=bar"}}));
}).then(function(r) {
is(typeof r, "undefined", "Searching for a request with an unknown Vary header should not succeed");
// Ensure that searching with a non-matching value for the Custom header but with ignoreVary set succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom": "foo=bar"}}),
{ignoreVary: true});
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
});
}
function testBasicKeys() {
function checkRequest(reqs) {
is(reqs.length, 1, "One request expected");
ok(reqs[0].url.indexOf(requestURL) >= 0, "The correct request expected");
ok(reqs[0].headers.get("WhatToVary"), "Custom", "The correct request headers expected");
}
var test;
return setupTest({"WhatToVary": "Custom"})
.then(function(t) {
test = t;
// Ensure that searching without specifying a Custom header succeeds.
return test.cache.keys(requestURL);
}).then(function(r) {
return checkRequest(r);
}).then(function() {
// Ensure that searching with a non-matching value for the Custom header fails.
return test.cache.keys(new Request(requestURL, {headers: {"Custom": "foo=bar"}}));
}).then(function(r) {
is(r.length, 0, "Searching for a request with an unknown Vary header should not succeed");
// Ensure that searching with a non-matching value for the Custom header but with ignoreVary set succeeds.
return test.cache.keys(new Request(requestURL, {headers: {"Custom": "foo=bar"}}),
{ignoreVary: true});
}).then(function(r) {
return checkRequest(r);
});
}
function testStar() {
function ensurePromiseRejected(promise) {
return promise
.then(function() {
ok(false, "Promise should be rejected");
}, function(err) {
is(err.name, "TypeError", "Attempting to store a Response with a Vary:* header must fail");
});
}
var test;
return new Promise(function(resolve, reject) {
var cache;
caches.open(name).then(function(c) {
cache = c;
Promise.all([
ensurePromiseRejected(
cache.add(new Request(requestURL + "1", {headers: {"WhatToVary": "*"}}))),
ensurePromiseRejected(
cache.addAll([
new Request(requestURL + "2", {headers: {"WhatToVary": "*"}}),
requestURL + "3",
])),
ensurePromiseRejected(
fetch(new Request(requestURL + "4", {headers: {"WhatToVary": "*"}}))
.then(function(response) {
return cache.put(requestURL + "4", response);
})),
ensurePromiseRejected(
cache.add(new Request(requestURL + "5", {headers: {"WhatToVary": "*,User-Agent"}}))),
ensurePromiseRejected(
cache.addAll([
new Request(requestURL + "6", {headers: {"WhatToVary": "*,User-Agent"}}),
requestURL + "7",
])),
ensurePromiseRejected(
fetch(new Request(requestURL + "8", {headers: {"WhatToVary": "*,User-Agent"}}))
.then(function(response) {
return cache.put(requestURL + "8", response);
})),
ensurePromiseRejected(
cache.add(new Request(requestURL + "9", {headers: {"WhatToVary": "User-Agent,*"}}))),
ensurePromiseRejected(
cache.addAll([
new Request(requestURL + "10", {headers: {"WhatToVary": "User-Agent,*"}}),
requestURL + "10",
])),
ensurePromiseRejected(
fetch(new Request(requestURL + "11", {headers: {"WhatToVary": "User-Agent,*"}}))
.then(function(response) {
return cache.put(requestURL + "11", response);
})),
]).then(reject, resolve);
});
});
}
function testMatch() {
var test;
return setupTest({"WhatToVary": "Custom", "Custom": "foo=bar"})
.then(function(t) {
test = t;
// Ensure that searching with a different Custom header fails.
return test.cache.match(new Request(requestURL, {headers: {"Custom": "bar=baz"}}));
}).then(function(r) {
is(typeof r, "undefined", "Searching for a request with a non-matching Custom header should not succeed");
// Ensure that searching with the same Custom header succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom": "foo=bar"}}));
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
});
}
function testInvalidHeaderName() {
var test;
return setupTest({"WhatToVary": "Foo/Bar, Custom-User-Agent"})
.then(function(t) {
test = t;
// Ensure that searching with a different User-Agent header fails.
return test.cache.match(new Request(requestURL, {headers: {"Custom-User-Agent": "MyUA"}}));
}).then(function(r) {
is(typeof r, "undefined", "Searching for a request with a non-matching Custom-User-Agent header should not succeed");
// Ensure that searching with a different Custom-User-Agent header but with ignoreVary succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom-User-Agent": "MyUA"}}),
{ignoreVary: true});
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
}).then(function() {
// Ensure that we do not mistakenly recognize the tokens in the invalid header name.
return test.cache.match(new Request(requestURL, {headers: {"Foo": "foobar"}}));
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
});
}
function testMultipleHeaders() {
var test;
return setupTest({"WhatToVary": "Custom-Referer,\tCustom-Accept-Encoding"})
.then(function(t) {
test = t;
// Ensure that searching with a different Referer header fails.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Referer": "https://somesite.com/"}}));
}).then(function(r) {
is(typeof r, "undefined", "Searching for a request with a non-matching Custom-Referer header should not succeed");
// Ensure that searching with a different Custom-Referer header but with ignoreVary succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Referer": "https://somesite.com/"}}),
{ignoreVary: true});
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
}).then(function() {
// Ensure that searching with a different Custom-Accept-Encoding header fails.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Accept-Encoding": "myencoding"}}));
}).then(function(r) {
is(typeof r, "undefined", "Searching for a request with a non-matching Custom-Accept-Encoding header should not succeed");
// Ensure that searching with a different Custom-Accept-Encoding header but with ignoreVary succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Accept-Encoding": "myencoding"}}),
{ignoreVary: true});
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
}).then(function() {
// Ensure that searching with an empty Custom-Referer header succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Referer": ""}}));
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
}).then(function() {
// Ensure that searching with an empty Custom-Accept-Encoding header succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Accept-Encoding": ""}}));
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
}).then(function() {
// Ensure that searching with an empty Custom-Referer header but with a different Custom-Accept-Encoding header fails.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Referer": "",
"Custom-Accept-Encoding": "myencoding"}}));
}).then(function(r) {
is(typeof r, "undefined", "Searching for a request with a non-matching Custom-Accept-Encoding header should not succeed");
// Ensure that searching with an empty Custom-Referer header but with a different Custom-Accept-Encoding header and ignoreVary succeeds.
return test.cache.match(new Request(requestURL, {headers: {"Custom-Referer": "",
"Custom-Accept-Encoding": "myencoding"}}),
{ignoreVary: true});
}).then(function(r) {
return checkResponse(r, test.response, test.responseText);
});
}
function testMultipleCacheEntries() {
var test;
return setupTestMultipleEntries([
{"WhatToVary": "Accept-Language", "Accept-Language": "en-US"},
{"WhatToVary": "Accept-Language", "Accept-Language": "en-US, fa-IR"},
]).then(function(t) {
test = t;
return test.cache.matchAll();
}).then(function (r) {
is(r.length, 2, "Two cache entries should be stored in the DB");
// Ensure that searching without specifying an Accept-Language header fails.
return test.cache.matchAll(requestURL);
}).then(function(r) {
is(r.length, 0, "Searching for a request without specifying an Accept-Language header should not succeed");
// Ensure that searching without specifying an Accept-Language header but with ignoreVary succeeds.
return test.cache.matchAll(requestURL, {ignoreVary: true});
}).then(function(r) {
return Promise.all([
checkResponse(r[0], test.response[0], test.responseText[0]),
checkResponse(r[1], test.response[1], test.responseText[1]),
]);
}).then(function() {
// Ensure that searching with Accept-Language: en-US succeeds.
return test.cache.matchAll(new Request(requestURL, {headers: {"Accept-Language": "en-US"}}));
}).then(function(r) {
is(r.length, 1, "One cache entry should be found");
return checkResponse(r[0], test.response[0], test.responseText[0]);
}).then(function() {
// Ensure that searching with Accept-Language: en-US,fa-IR succeeds.
return test.cache.matchAll(new Request(requestURL, {headers: {"Accept-Language": "en-US, fa-IR"}}));
}).then(function(r) {
is(r.length, 1, "One cache entry should be found");
return checkResponse(r[0], test.response[1], test.responseText[1]);
}).then(function() {
// Ensure that searching with a valid Accept-Language header but with ignoreVary returns both entries.
return test.cache.matchAll(new Request(requestURL, {headers: {"Accept-Language": "en-US"}}),
{ignoreVary: true});
}).then(function(r) {
return Promise.all([
checkResponse(r[0], test.response[0], test.responseText[0]),
checkResponse(r[1], test.response[1], test.responseText[1]),
]);
}).then(function() {
// Ensure that searching with Accept-Language: fa-IR fails.
return test.cache.matchAll(new Request(requestURL, {headers: {"Accept-Language": "fa-IR"}}));
}).then(function(r) {
is(r.length, 0, "Searching for a request with a different Accept-Language header should not succeed");
// Ensure that searching with Accept-Language: fa-IR but with ignoreVary should succeed.
return test.cache.matchAll(new Request(requestURL, {headers: {"Accept-Language": "fa-IR"}}),
{ignoreVary: true});
}).then(function(r) {
is(r.length, 2, "Two cache entries should be found");
return Promise.all([
checkResponse(r[0], test.response[0], test.responseText[0]),
checkResponse(r[1], test.response[1], test.responseText[1]),
]);
});
}
// Make sure to clean up after each test step.
function step(testPromise) {
return testPromise.then(function() {
caches.delete(name);
}, function() {
caches.delete(name);
});
}
step(testBasics()).then(function() {
return step(testBasicKeys());
}).then(function() {
return step(testStar());
}).then(function() {
return step(testMatch());
}).then(function() {
return step(testInvalidHeaderName());
}).then(function() {
return step(testMultipleHeaders());
}).then(function() {
return step(testMultipleCacheEntries());
}).then(function() {
testDone();
});

View file

@ -0,0 +1,235 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test Cache with QuotaManager Restart</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="large_url_list.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script class="testbody" type="text/javascript">
function setupTestIframe() {
return new Promise(function(resolve) {
var iframe = document.createElement("iframe");
iframe.src = "empty.html";
iframe.onload = function() {
window.caches = iframe.contentWindow.caches;
resolve();
};
document.body.appendChild(iframe);
});
}
function clearStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var request = qms.clearStoragesForPrincipal(principal);
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function storageUsage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var cb = SpecialPowers.wrapCallback(function(request) {
var result = request.result;
resolve(result.usage, result.fileUsage);
});
qms.getUsageForPrincipal(principal, cb);
});
}
function groupUsage() {
return new Promise(function(resolve, reject) {
navigator.storage.estimate().then(storageEstimation => {
resolve(storageEstimation.usage, 0);
});
});
}
function workerGroupUsage() {
return new Promise(function(resolve, reject) {
function workerScript() {
navigator.storage.estimate().then(storageEstimation => {
postMessage(storageEstimation.usage);
});
}
let url =
URL.createObjectURL(new Blob(["(", workerScript.toSource(), ")()"]));
let worker = new Worker(url);
worker.onmessage = function (e) {
resolve(e.data, 0);
};
});
}
function resetStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var request = qms.reset();
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function gc() {
return new Promise(function(resolve, reject) {
SpecialPowers.exactGC(resolve);
});
}
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.caches.testing.enabled", true],
["dom.quotaManager.testing", true],
["dom.storageManager.enabled", true]],
}, function() {
var name = 'orphanedBodyOwner';
var cache = null;
var response = null;
var initialUsage = 0;
var fullUsage = 0;
var resetUsage = 0;
var endUsage = 0;
var url = 'test_cache_add.js';
// start from a fresh origin directory so other tests do not influence our
// results
setupTestIframe().then(function() {
return clearStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
is(0, usage, 'disk usage should be zero to start');
})
// Initialize and populate an initial cache to get the base sqlite pages
// and directory structure allocated.
.then(function() {
return caches.open(name);
}).then(function(c) {
return c.add(url);
}).then(function() {
return gc();
}).then(function() {
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, 'cache should be deleted');
// This is a bit superfluous, but its necessary to make sure the Cache is
// fully deleted before we proceed. The deletion actually takes place in
// two async steps. We don't want to resetStorage() until the second step
// has taken place. This extra Cache operation ensure that all the
// runnables have been flushed through the threads, etc.
return caches.has(name);
})
// Now measure initial disk usage
.then(function() {
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
initialUsage = usage;
})
// Now re-populate the Cache object
.then(function() {
return caches.open(name);
}).then(function(c) {
cache = c;
return cache.add(url);
})
// Get a reference to the body we've stored in the Cache.
.then(function() {
return cache.match(url);
}).then(function(r) {
response = r;
return cache.delete(url);
}).then(function(result) {
ok(result, "Cache entry should be deleted");
})
// Reset the quota dir while the cache entry is deleted, but still referenced
// from the DOM. This forces the body to be orphaned.
.then(function() {
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
fullUsage = usage;
ok(fullUsage > initialUsage, 'disk usage should have grown');
})
// Test groupUsage()
.then(function() {
return resetStorage();
}).then(function() {
return groupUsage();
}).then(function(usage) {
fullUsage = usage;
ok(fullUsage > initialUsage, 'disk group usage should have grown');
})
// Test workerGroupUsage()
.then(function() {
return resetStorage();
}).then(function() {
return workerGroupUsage();
}).then(function(usage) {
fullUsage = usage;
ok(fullUsage > initialUsage, 'disk group usage on worker should have grown');
})
// Now perform a new Cache operation that will reopen the origin. This
// should clean up the orphaned body.
.then(function() {
return caches.match(url);
}).then(function(r) {
ok(!r, 'response should not exist in storage');
})
// Finally, verify orphaned data was cleaned up by re-checking the disk
// usage. Reset the storage first to ensure any WAL transaction files
// are flushed before measuring the usage.
.then(function() {
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
endUsage = usage;
dump("### ### initial:" + initialUsage + ", full:" + fullUsage +
", end:" + endUsage + "\n");
ok(endUsage < fullUsage, 'disk usage should have shrank');
is(endUsage, initialUsage, 'disk usage should return to original');
})
// Verify that the stale, orphaned response cannot be put back into
// the cache.
.then(function() {
ok(!response.bodyUsed, 'response body should not be considered used');
return cache.put(url, response).then(function() {
ok(false, 'Should not be able to store stale orphaned body.');
}).catch(function(e) {
is(e.name, 'TypeError', 'storing a stale orphaned body should throw TypeError');
});
}).then(function() {
ok(response.bodyUsed, 'attempting to store response should mark body used');
})
.then(function() {
SimpleTest.finish();
});
});
</script>
</body>
</html>

View file

@ -0,0 +1,165 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test Cache with QuotaManager Restart</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="large_url_list.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script class="testbody" type="text/javascript">
function setupTestIframe() {
return new Promise(function(resolve) {
var iframe = document.createElement("iframe");
iframe.src = "empty.html";
iframe.onload = function() {
window.caches = iframe.contentWindow.caches;
resolve();
};
document.body.appendChild(iframe);
});
}
function clearStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var request = qms.clearStoragesForPrincipal(principal);
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function storageUsage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var cb = SpecialPowers.wrapCallback(function(request) {
var result = request.result;
resolve(result.usage, result.fileUsage);
});
qms.getUsageForPrincipal(principal, cb);
});
}
function resetStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var request = qms.reset();
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function gc() {
return new Promise(function(resolve, reject) {
SpecialPowers.exactGC(resolve);
});
}
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.caches.testing.enabled", true],
["dom.quotaManager.testing", true]],
}, function() {
var name = 'toBeOrphaned';
var cache = null;
var initialUsage = 0;
var fullUsage = 0;
var resetUsage = 0;
var endUsage = 0;
var url = 'test_cache_add.js';
// start from a fresh origin directory so other tests do not influence our
// results
setupTestIframe().then(function() {
return clearStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
is(0, usage, 'disk usage should be zero to start');
})
// Initialize and populate an initial cache to get the base sqlite pages
// and directory structure allocated.
.then(function() {
return caches.open(name);
}).then(function(c) {
return c.add(url);
}).then(function() {
return gc();
}).then(function() {
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, 'cache should be deleted');
// This is a bit superfluous, but its necessary to make sure the Cache is
// fully deleted before we proceed. The deletion actually takes place in
// two async steps. We don't want to resetStorage() until the second step
// has taken place. This extra Cache operation ensure that all the
// runnables have been flushed through the threads, etc.
return caches.has(name);
})
// Now measure initial disk usage
.then(function() {
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
initialUsage = usage;
})
// Now re-populate the Cache object
.then(function() {
return caches.open(name);
}).then(function(c) {
cache = c;
return cache.add(url);
}).then(function() {
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, 'cache should be deleted');
})
// Reset the quota dir while the cache is deleted, but still referenced
// from the DOM. This forces it to be orphaned.
.then(function() {
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
fullUsage = usage;
ok(fullUsage > initialUsage, 'disk usage should have grown');
})
// Now perform a new Cache operation that will reopen the origin. This
// should clean up the orphaned Cache data.
.then(function() {
return caches.has(name);
}).then(function(result) {
ok(!result, 'cache should not exist in storage');
})
// Finally, verify orphaned data was cleaned up by re-checking the disk
// usage. Reset the storage first to ensure any WAL transaction files
// are flushed before measuring the usage.
.then(function() {
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
endUsage = usage;
dump("### ### initial:" + initialUsage + ", full:" + fullUsage +
", end:" + endUsage + "\n");
ok(endUsage < fullUsage, 'disk usage should have shrank');
is(endUsage, initialUsage, 'disk usage should return to original');
SimpleTest.finish();
});
});
</script>
</body>
</html>

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test what happens when you overwrite a cache entry</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_overwrite.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,47 @@
var requestURL = "//mochi.test:8888/tests/dom/cache/test/mochitest/mirror.sjs?" + context;
var response;
var c;
var responseText;
var name = "match-mirror" + context;
function checkResponse(r) {
ok(r !== response, "The objects should not be the same");
is(r.url, response.url.replace("#fragment", ""),
"The URLs should be the same");
is(r.status, response.status, "The status codes should be the same");
is(r.type, response.type, "The response types should be the same");
is(r.ok, response.ok, "Both responses should have succeeded");
is(r.statusText, response.statusText,
"Both responses should have the same status text");
is(r.headers.get("Mirrored"), response.headers.get("Mirrored"),
"Both responses should have the same Mirrored header");
return r.text().then(function(text) {
is(text, responseText, "The response body should be correct");
});
}
fetch(new Request(requestURL, {headers: {"Mirror": "bar"}})).then(function(r) {
is(r.headers.get("Mirrored"), "bar", "The server should give back the correct header");
response = r;
return response.text();
}).then(function(text) {
responseText = text;
return caches.open(name);
}).then(function(cache) {
c = cache;
return c.add(new Request(requestURL, {headers: {"Mirror": "foo"}}));
}).then(function() {
// Overwrite the request, to replace the entry stored in response_headers
// with a different value.
return c.add(new Request(requestURL, {headers: {"Mirror": "bar"}}));
}).then(function() {
return c.matchAll();
}).then(function(r) {
is(r.length, 1, "Only one request should be in the cache");
return checkResponse(r[0]);
}).then(function() {
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The cache should be deleted successfully");
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate Interfaces Exposed to Workers</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_put.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,50 @@
var url = 'test_cache.js';
var cache;
var fetchResponse;
Promise.all([fetch(url),
caches.open('putter' + context)]).then(function(results) {
fetchResponse = results[0];
cache = results[1];
return cache.put(url, fetchResponse.clone());
}).then(function(result) {
is(undefined, result, 'Successful put() should resolve undefined');
return cache.match(url);
}).then(function(response) {
ok(response, 'match() should find resppnse that was previously put()');
ok(response.url.endsWith(url), 'matched response should match original url');
return Promise.all([fetchResponse.text(),
response.text()]);
}).then(function(results) {
// suppress large assert spam unless it's relevent
if (results[0] !== results[1]) {
is(results[0], results[1], 'stored response body should match original');
}
// Now, try to overwrite the request with a different response object.
return cache.put(url, new Response("overwritten"));
}).then(function() {
return cache.matchAll(url);
}).then(function(result) {
is(result.length, 1, "Only one entry should exist");
return result[0].text();
}).then(function(body) {
is(body, "overwritten", "The cache entry should be successfully overwritten");
// Now, try to write a URL with a fragment
return cache.put(url + "#fragment", new Response("more overwritten"));
}).then(function() {
return cache.matchAll(url + "#differentFragment");
}).then(function(result) {
is(result.length, 1, "Only one entry should exist");
return result[0].text();
}).then(function(body) {
is(body, "more overwritten", "The cache entry should be successfully overwritten");
// TODO: Verify that trying to store a response with an error raises a TypeError
// when bug 1147178 is fixed.
return caches.delete('putter' + context);
}).then(function(deleted) {
ok(deleted, "The cache should be deleted successfully");
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Ensure that using Cache.put to overwrite an entry will change its insertion order</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_put_reorder.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,31 @@
var name = "putreorder" + context;
var c;
var reqs = [
"//mochi.test:8888/?foo" + context,
"//mochi.test:8888/?bar" + context,
"//mochi.test:8888/?baz" + context,
];
caches.open(name).then(function(cache) {
c = cache;
return c.addAll(reqs);
}).then(function() {
return c.put(reqs[1], new Response("overwritten"));
}).then(function() {
return c.keys();
}).then(function(keys) {
is(keys.length, 3, "Correct number of entries expected");
ok(keys[0].url.indexOf(reqs[0]) >= 0, "The first entry should be untouched");
ok(keys[2].url.indexOf(reqs[1]) >= 0, "The second entry should be moved to the end");
ok(keys[1].url.indexOf(reqs[2]) >= 0, "The third entry should now be the second one");
return c.match(reqs[1]);
}).then(function(r) {
return r.text();
}).then(function(body) {
is(body, "overwritten", "The body should be overwritten");
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The cache should be deleted successfully");
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate Cache storage of redirect responses</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_redirect.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,14 @@
let cache;
let url = 'foo.html';
let redirectURL = 'http://example.com/foo-bar.html';
caches.open('redirect-' + context).then(c => {
cache = c;
var response = Response.redirect(redirectURL);
is(response.headers.get('Location'), redirectURL);
return cache.put(url, response);
}).then(_ => {
return cache.match(url);
}).then(response => {
is(response.headers.get('Location'), redirectURL);
testDone();
});

View file

@ -0,0 +1,20 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate the Cache.keys() method</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
runTests("test_cache_requestCache.js")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

View file

@ -0,0 +1,27 @@
var name = "requestCache" + context;
var c;
var reqWithoutCache = new Request("//mochi.test:8888/?noCache" + context);
var reqWithCache = new Request("//mochi.test:8888/?withCache" + context,
{cache: "force-cache"});
// Sanity check
is(reqWithoutCache.cache, "default", "Correct default value");
is(reqWithCache.cache, "force-cache", "Correct value set by the ctor");
caches.open(name).then(function(cache) {
c = cache;
return c.addAll([reqWithoutCache, reqWithCache]);
}).then(function() {
return c.keys();
}).then(function(keys) {
is(keys.length, 2, "Correct number of requests");
is(keys[0].url, reqWithoutCache.url, "Correct URL");
is(keys[0].cache, reqWithoutCache.cache, "Correct cache attribute");
is(keys[1].url, reqWithCache.url, "Correct URL");
is(keys[1].cache, reqWithCache.cache, "Correct cache attribute");
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The cache should be successfully deleted");
testDone();
});

View file

@ -0,0 +1,70 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test Cache with QuotaManager Restart</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script class="testbody" type="text/javascript">
function setupTestIframe() {
return new Promise(function(resolve) {
var iframe = document.createElement("iframe");
iframe.src = "empty.html";
iframe.onload = function() {
window.caches = iframe.contentWindow.caches;
resolve();
};
document.body.appendChild(iframe);
});
}
function resetStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var request = qms.reset();
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.caches.testing.enabled", true],
["dom.quotaManager.testing", true]],
}, function() {
var name = 'foo';
var url = './test_cache_add.js';
var cache;
setupTestIframe().then(function() {
return caches.open(name);
}).then(function(c) {
cache = c;
return cache.add(url);
}).then(function() {
return resetStorage();
}).then(function() {
return cache.match(url).then(function(resp) {
ok(false, 'old cache reference should not work after reset');
}).catch(function(err) {
ok(true, 'old cache reference should not work after reset');
});
}).then(function() {
return caches.open(name);
}).then(function(c) {
cache = c;
return cache.match(url);
}).then(function(resp) {
ok(!!resp, 'cache should work after QM reset');
return caches.delete(name);
}).then(function(success) {
ok(success, 'cache should be deleted');
SimpleTest.finish();
});
});
</script>
</body>
</html>

View file

@ -0,0 +1,132 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test Cache with QuotaManager Restart</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="large_url_list.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script class="testbody" type="text/javascript">
function setupTestIframe() {
return new Promise(function(resolve) {
var iframe = document.createElement("iframe");
iframe.src = "empty.html";
iframe.onload = function() {
window.caches = iframe.contentWindow.caches;
resolve();
};
document.body.appendChild(iframe);
});
}
function clearStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var request = qms.clearStoragesForPrincipal(principal);
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function storageUsage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var principal = SpecialPowers.wrap(document).nodePrincipal;
var cb = SpecialPowers.wrapCallback(function(request) {
var result = request.result;
resolve(result.usage, result.fileUsage);
});
qms.getUsageForPrincipal(principal, cb);
});
}
function resetStorage() {
return new Promise(function(resolve, reject) {
var qms = SpecialPowers.Services.qms;
var request = qms.reset();
var cb = SpecialPowers.wrapCallback(resolve);
request.callback = cb;
});
}
function gc() {
return new Promise(function(resolve, reject) {
SpecialPowers.exactGC(resolve);
});
}
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.caches.testing.enabled", true],
["dom.quotaManager.testing", true]],
}, function() {
var name = 'foo';
var cache = null;
var initialUsage = 0;
var fullUsage = 0;
var endUsage = 0;
// start from a fresh origin directory so other tests do not influence our
// results
setupTestIframe().then(function() {
return clearStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
is(0, usage, 'disk usage should be zero to start');
return caches.open(name);
}).then(function(c) {
cache = c;
return storageUsage();
}).then(function(usage) {
initialUsage = usage;
return Promise.all(largeUrlList.map(function(url) {
return cache.put(new Request(url), new Response());
}));
}).then(function() {
return cache.keys();
}).then(function(keyList) {
is(keyList.length, largeUrlList.length, 'Large URL list is stored in cache');
cache = null;
// Ensure the Cache DOM object is gone before proceeding. If its alive
// it will keep the related entries on-disk as well.
return gc();
}).then(function() {
// reset the quota manager storage to ensure the DB connection is flushed
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
fullUsage = usage;
ok(fullUsage > initialUsage, 'disk usage should have grown');
return caches.delete(name);
}).then(function(result) {
ok(result, 'cache should be deleted');
// This is a bit superfluous, but its necessary to make sure the Cache is
// fully deleted before we proceed. The deletion actually takes place in
// two async steps. We don't want to resetStorage() until the second step
// has taken place. This extra Cache operation ensure that all the
// runnables have been flushed through the threads, etc.
return caches.has(name);
}).then(function(result) {
ok(!result, 'cache should not exist in storage');
// reset the quota manager storage to ensure the DB connection is flushed
return resetStorage();
}).then(function() {
return storageUsage();
}).then(function(usage) {
endUsage = usage;
dump("### ### initial:" + initialUsage + ", full:" + fullUsage +
", end:" + endUsage + "\n");
ok(endUsage < (fullUsage / 2), 'disk usage should have shrank significantly');
ok(endUsage > initialUsage, 'disk usage should not shrink back to orig size');
SimpleTest.finish();
});
});
</script>
</body>
</html>

View file

@ -0,0 +1,40 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test Cache with QuotaManager Restart</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="large_url_list.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script class="testbody" type="text/javascript">
function setupTestIframe() {
return new Promise(function(resolve) {
var iframe = document.createElement("iframe");
iframe.src = "empty.html";
iframe.onload = function() {
window.caches = iframe.contentWindow.caches;
resolve();
};
document.body.appendChild(iframe);
});
}
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true]],
}, function() {
setupTestIframe().then(function() {
return caches.open('foo');
}).then(function(usage) {
ok(false, 'caches should not be usable in untrusted http origin');
}).catch(function(err) {
is(err.name, 'SecurityError', 'caches should reject with SecurityError');
SimpleTest.finish();
});
});
</script>
</body>
</html>

View file

@ -0,0 +1,22 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Test the CacheStorage API</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
<script type="text/javascript" src="driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
// These tests can only be run in sequential mode because we need to be able
// to rely on the global state of the CacheStorage at all times.
runTests("test_caches.js", "sequential")
.then(function() {
SimpleTest.finish();
});
</script>
</body>
</html>

122
dom/cache/test/mochitest/test_caches.js vendored Normal file
View file

@ -0,0 +1,122 @@
function arraysHaveSameContent(arr1, arr2) {
if (arr1.length != arr2.length) {
return false;
}
return arr1.every(function(value, index) {
return arr2[index] === value;
});
}
function testHas() {
var name = "caches-has" + context;
return caches.has(name).then(function(has) {
ok(!has, name + " should not exist yet");
return caches.open(name);
}).then(function(c) {
return caches.has(name);
}).then(function(has) {
ok(has, name + " should now exist");
return caches.delete(name);
}).then(function(deleted) {
ok(deleted, "The deletion should finish successfully");
return caches.has(name);
}).then(function(has) {
ok(!has, name + " should not exist any more");
});
}
function testKeys() {
var names = [
// The names here are intentionally unsorted, to ensure the insertion order
// and make sure we don't confuse it with an alphabetically sorted list.
"caches-keys4" + context,
"caches-keys0" + context,
"caches-keys1" + context,
"caches-keys3" + context,
];
return caches.keys().then(function(keys) {
is(keys.length, 0, "No keys should exist yet");
return Promise.all(names.map(function(name) {
return caches.open(name);
}));
}).then(function() {
return caches.keys();
}).then(function(keys) {
ok(arraysHaveSameContent(keys, names), "Keys must match in insertion order");
return Promise.all(names.map(function(name) {
return caches.delete(name);
}));
}).then(function(deleted) {
ok(arraysHaveSameContent(deleted, [true, true, true, true]), "All deletions must succeed");
return caches.keys();
}).then(function(keys) {
is(keys.length, 0, "No keys should exist any more");
});
}
function testMatchAcrossCaches() {
var tests = [
// The names here are intentionally unsorted, to ensure the insertion order
// and make sure we don't confuse it with an alphabetically sorted list.
{
name: "caches-xmatch5" + context,
request: "//mochi.test:8888/?5" + context,
},
{
name: "caches-xmatch2" + context,
request: "//mochi.test:8888/tests/dom/cache/test/mochitest/test_caches.js?2" + context,
},
{
name: "caches-xmatch4" + context,
request: "//mochi.test:8888/?4" + context,
},
];
return Promise.all(tests.map(function(test) {
return caches.open(test.name).then(function(c) {
return c.add(test.request);
});
})).then(function() {
return caches.match("//mochi.test:8888/?5" + context, {ignoreSearch: true});
}).then(function(match) {
ok(match.url.indexOf("?5") > 0, "Match should come from the first cache");
return caches.delete("caches-xmatch2" + context); // This should not change anything!
}).then(function(deleted) {
ok(deleted, "Deletion should finish successfully");
return caches.match("//mochi.test:8888/?" + context, {ignoreSearch: true});
}).then(function(match) {
ok(match.url.indexOf("?5") > 0, "Match should still come from the first cache");
return caches.delete("caches-xmatch5" + context); // This should eliminate the first match!
}).then(function(deleted) {
ok(deleted, "Deletion should finish successfully");
return caches.match("//mochi.test:8888/?" + context, {ignoreSearch: true});
}).then(function(match) {
ok(match.url.indexOf("?4") > 0, "Match should come from the third cache");
return caches.delete("caches-xmatch4" + context); // Game over!
}).then(function(deleted) {
ok(deleted, "Deletion should finish successfully");
return caches.match("//mochi.test:8888/?" + context, {ignoreSearch: true});
}).then(function(match) {
is(typeof match, "undefined", "No matches should be found");
});
}
function testDelete() {
return caches.delete("delete" + context).then(function(deleted) {
ok(!deleted, "Attempting to delete a non-existing cache should fail");
return caches.open("delete" + context);
}).then(function() {
return caches.delete("delete" + context);
}).then(function(deleted) {
ok(deleted, "Delete should now succeed");
});
}
testHas().then(function() {
return testKeys();
}).then(function() {
return testMatchAcrossCaches();
}).then(function() {
return testDelete();
}).then(function() {
testDone();
});

View file

@ -0,0 +1,44 @@
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
<!DOCTYPE HTML>
<html>
<head>
<title>Validate Interfaces Exposed to Workers</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.caches.testing.enabled", true]],
}, function() {
// attach to a different origin's CacheStorage
var url = 'http://example.com/';
var storage = SpecialPowers.createChromeCache('content', url);
// verify we can use the other origin's CacheStorage as normal
var req = new Request('http://example.com/index.html');
var res = new Response('hello world');
var cache;
storage.open('foo').then(function(c) {
cache = c;
ok(cache, 'storage should create cache');
return cache.put(req, res.clone());
}).then(function() {
return cache.match(req);
}).then(function(foundResponse) {
return Promise.all([res.text(), foundResponse.text()]);
}).then(function(results) {
is(results[0], results[1], 'cache should contain response');
return storage.delete('foo');
}).then(function(deleted) {
ok(deleted, 'storage should delete cache');
SimpleTest.finish();
});
});
</script>
</body>
</html>

9
dom/cache/test/mochitest/vary.sjs vendored Normal file
View file

@ -0,0 +1,9 @@
function handleRequest(request, response) {
response.setStatusLine(request.httpVersion, 200, "OK");
var header = "no WhatToVary header";
if (request.hasHeader("WhatToVary")) {
header = request.getHeader("WhatToVary");
response.setHeader("Vary", header);
}
response.write(header);
}

View file

@ -0,0 +1,86 @@
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// Utility script for writing worker tests. In your main document do:
//
// <script type="text/javascript" src="worker_driver.js"></script>
// <script type="text/javascript">
// workerTestExec('myWorkerTestCase.js')
// </script>
//
// This will then spawn a worker, define some utility functions, and then
// execute the code in myWorkerTestCase.js. You can then use these
// functions in your worker-side test:
//
// ok() - like the SimpleTest assert
// is() - like the SimpleTest assert
// workerTestDone() - like SimpleTest.finish() indicating the test is complete
//
// There are also some functions for requesting information that requires
// SpecialPowers or other main-thread-only resources:
//
// workerTestGetPrefs() - request an array of prefs value from the main thread
// workerTestGetPermissions() - request an array permissions from the MT
// workerTestGetVersion() - request the current version string from the MT
// workerTestGetUserAgent() - request the user agent string from the MT
//
// For an example see test_worker_interfaces.html and test_worker_interfaces.js.
function workerTestExec(script) {
return new Promise(function(resolve, reject) {
var worker = new Worker('worker_wrapper.js');
worker.onmessage = function(event) {
is(event.data.context, "Worker",
"Correct context for messages received on the worker");
if (event.data.type == 'finish') {
worker.terminate();
SpecialPowers.forceGC();
resolve();
} else if (event.data.type == 'status') {
ok(event.data.status, event.data.context + ": " + event.data.msg);
} else if (event.data.type == 'getPrefs') {
var result = {};
event.data.prefs.forEach(function(pref) {
result[pref] = SpecialPowers.Services.prefs.getBoolPref(pref);
});
worker.postMessage({
type: 'returnPrefs',
prefs: event.data.prefs,
result: result
});
} else if (event.data.type == 'getPermissions') {
var result = {};
event.data.permissions.forEach(function(permission) {
result[permission] = SpecialPowers.hasPermission(permission, window.document);
});
worker.postMessage({
type: 'returnPermissions',
permissions: event.data.permissions,
result: result
});
} else if (event.data.type == 'getVersion') {
var result = SpecialPowers.Cc['@mozilla.org/xre/app-info;1'].getService(SpecialPowers.Ci.nsIXULAppInfo).version;
worker.postMessage({
type: 'returnVersion',
result: result
});
} else if (event.data.type == 'getUserAgent') {
worker.postMessage({
type: 'returnUserAgent',
result: navigator.userAgent
});
}
}
worker.onerror = function(event) {
reject('Worker had an error: ' + event.data);
};
worker.postMessage({ script: script });
});
}

View file

@ -0,0 +1,129 @@
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// ServiceWorker equivalent of worker_wrapper.js.
var client;
var context;
function ok(a, msg) {
client.postMessage({type: 'status', status: !!a,
msg: a + ": " + msg, context: context});
}
function is(a, b, msg) {
client.postMessage({type: 'status', status: a === b,
msg: a + " === " + b + ": " + msg, context: context });
}
function workerTestArrayEquals(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length != b.length) {
return false;
}
for (var i = 0, n = a.length; i < n; ++i) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function testDone() {
client.postMessage({ type: 'finish', context: context });
}
function workerTestGetPrefs(prefs, cb) {
addEventListener('message', function workerTestGetPrefsCB(e) {
if (e.data.type != 'returnPrefs' ||
!workerTestArrayEquals(prefs, e.data.prefs)) {
return;
}
removeEventListener('message', workerTestGetPrefsCB);
cb(e.data.result);
});
client.postMessage({
type: 'getPrefs',
context: context,
prefs: prefs
});
}
function workerTestGetPermissions(permissions, cb) {
addEventListener('message', function workerTestGetPermissionsCB(e) {
if (e.data.type != 'returnPermissions' ||
!workerTestArrayEquals(permissions, e.data.permissions)) {
return;
}
removeEventListener('message', workerTestGetPermissionsCB);
cb(e.data.result);
});
client.postMessage({
type: 'getPermissions',
context: context,
permissions: permissions
});
}
function workerTestGetVersion(cb) {
addEventListener('message', function workerTestGetVersionCB(e) {
if (e.data.type !== 'returnVersion') {
return;
}
removeEventListener('message', workerTestGetVersionCB);
cb(e.data.result);
});
client.postMessage({
context: context,
type: 'getVersion'
});
}
function workerTestGetUserAgent(cb) {
addEventListener('message', function workerTestGetUserAgentCB(e) {
if (e.data.type !== 'returnUserAgent') {
return;
}
removeEventListener('message', workerTestGetUserAgentCB);
cb(e.data.result);
});
client.postMessage({
context: context,
type: 'getUserAgent'
});
}
addEventListener('message', function workerWrapperOnMessage(e) {
removeEventListener('message', workerWrapperOnMessage);
var data = e.data;
function runScript() {
try {
importScripts(data.script);
} catch(e) {
client.postMessage({
type: 'status',
status: false,
context: context,
msg: 'worker failed to import ' + data.script + "; error: " + e.message
});
}
}
if ("ServiceWorker" in self) {
self.clients.matchAll().then(function(clients) {
for (var i = 0; i < clients.length; ++i) {
if (clients[i].url.indexOf("message_receiver.html") > -1) {
client = clients[i];
break;
}
}
if (!client) {
dump("We couldn't find the message_receiver window, the test will fail\n");
}
context = "ServiceWorker";
runScript();
});
} else {
client = self;
context = "Worker";
runScript();
}
});