Bug 940273 - Part 7 - Initial tests for Service Worker Cache. r=ehsan

This commit is contained in:
Ben Kelly 2015-03-02 14:24:00 +01:00
Родитель 8bf704b7d2
Коммит 3da9ec399c
11 изменённых файлов: 480 добавлений и 0 удалений

4
dom/cache/moz.build поставляемый
Просмотреть файл

@ -81,3 +81,7 @@ LOCAL_INCLUDES += [
FAIL_ON_WARNINGS = True
FINAL_LIBRARY = 'xul'
MOCHITEST_MANIFESTS += [
'test/mochitest/mochitest.ini',
]

12
dom/cache/test/mochitest/mochitest.ini поставляемый Normal file
Просмотреть файл

@ -0,0 +1,12 @@
[DEFAULT]
support-files =
test_cache.js
test_cache_add.js
test_cache_frame.html
test_cache_quick_close.js
worker_driver.js
worker_wrapper.js
[test_cache.html]
[test_cache_add.html]
[test_cache_quick_close.html]

37
dom/cache/test/mochitest/test_cache.html поставляемый Normal file
Просмотреть файл

@ -0,0 +1,37 @@
<!-- 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="worker_driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true],
["dom.fetch.enabled", true]]
}, function() {
var frame = document.getElementById("frame");
frame.src = "test_cache_frame.html";
frame.onload = function() {
var contentWindow = frame.contentWindow;
addEventListener("message", function(evt) {
ok(evt.data.success, "frame should have succeeded");
workerTestExec("test_cache.js");
});
contentWindow.postMessage({
type: "start"
}, "*");
}
});
</script>
</body>
</html>

60
dom/cache/test/mochitest/test_cache.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,60 @@
ok(!!caches, 'caches object should be available on global');
caches.open('snafu').then(function(openCache) {
ok(openCache instanceof Cache, 'cache object should be resolved from caches.open');
return caches.has('snafu');
}).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');
is(1, keys.length, 'caches.keys() should resolve to an array of length 1');
is(0, keys.indexOf('snafu'), 'caches.keys() should resolve to an array containing key');
return caches.delete('snafu');
}).then(function(deleteResult) {
ok(deleteResult, 'caches.delete() should resolve true');
return caches.has('snafu');
}).then(function(hasMissingCache) {
ok(!hasMissingCache, 'missing key should return false from has');
}).then(function() {
return caches.open('snafu');
}).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('snafu');
}).then(function(snafu) {
var req = './cachekey';
var res = new Response("Hello world");
return snafu.put('ftp://invalid', res).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() {
workerTestDone();
})

22
dom/cache/test/mochitest/test_cache_add.html поставляемый Normal 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>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="worker_driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true]]
}, function() {
workerTestExec("test_cache_add.js");
});
</script>
</body>
</html>

46
dom/cache/test/mochitest/test_cache_add.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,46 @@
var singleUrl = './test_cache_add.js';
var urlList = [
'./helloworld.txt',
'./foobar.txt',
'./test_cache.js'
];
var cache;
caches.open('adder').then(function(openCache) {
cache = openCache;
return cache.add('ftp://example.com/invalid');
}).catch(function (err) {
is(err.name, 'NetworkError', 'add() should throw NetworkError for invalid scheme');
return cache.addAll(['http://example.com/valid', 'ftp://example.com/invalid']);
}).catch(function (err) {
is(err.name, 'NetworkError', 'addAll() should throw NetworkError 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.');
});
workerTestDone();
}).catch(function(err) {
ok(false, 'Caught error: ' + err);
workerTestDone();
});

87
dom/cache/test/mochitest/test_cache_frame.html поставляемый Normal file
Просмотреть файл

@ -0,0 +1,87 @@
<!--
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
<head>
<title>Test for SharedWorker</title>
</head>
<body>
<script type="text/javascript">
"use strict";
addEventListener("message", function messageListener(evt) {
removeEventListener("message", messageListener);
var success = true;
var c = null
// 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.
var request = "http://example.com/hmm?q=foobar";
var response = new Response("This is some Response!");
success = success && !!caches;
caches.open("foobar").then(function(openCache) {
success = success && (openCache instanceof Cache);
c = openCache;
return c.put(request, response);
}).then(function(putResponse) {
success = success && putResponse === undefined;
return c.keys(request);
}).then(function(keys) {
success = success && !!keys;
success = success && keys.length === 1;
return c.keys();
}).then(function(keys) {
success = success && !!keys;
success = success && keys.length === 1;
return c.matchAll(request);
}).then(function(matchAllResponses) {
success = success && !!matchAllResponses &&
matchAllResponses.length === 1;
return c.match(request);
}).then(function(matchResponse) {
success = success && !!matchResponse;
return caches.match(request);
}).then(function(storageMatchResponse) {
success = success && !!storageMatchResponse;
return caches.match(request, {cacheName:"foobar"});
}).then(function(storageMatchResponse) {
success = success && !!storageMatchResponse;
var request2 = new Request("http://example.com/hmm?q=snafu");
return c.match(request2, {ignoreSearch:true});
}).then(function(match2Response) {
success = success && !!match2Response;
return c.delete(request);
}).then(function(deleteResult) {
success = success && deleteResult;
return c.keys();
}).then(function(keys) {
success = success && !!keys;
success = success && keys.length === 0;
return c.matchAll(request);
}).then(function(matchAll2Responses) {
success = success && !!matchAll2Responses &&
matchAll2Responses.length === 0;
return caches.has("foobar");
}).then(function(hasResult) {
success = success && hasResult;
return caches.keys();
}).then(function(keys) {
success = success && !!keys;
success = success && keys.length === 1;
success = success && keys.indexOf("foobar") === 0;
return caches.delete("foobar");
}).then(function(deleteResult) {
success = success && deleteResult;
return caches.has("foobar");
}).then(function(hasMissingCache) {
success = success && !hasMissingCache;
parent.postMessage({
type: "result",
success: success
}, "*");
});
});
</script>
</body>
</html>

22
dom/cache/test/mochitest/test_cache_quick_close.html поставляемый Normal 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>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="worker_driver.js"></script>
</head>
<body>
<iframe id="frame"></iframe>
<script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish();
SpecialPowers.pushPrefEnv({
"set": [["dom.caches.enabled", true]]
}, function() {
workerTestExec("test_cache_quick_close.js");
});
</script>
</body>
</html>

6
dom/cache/test/mochitest/test_cache_quick_close.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,6 @@
caches.open('closer').then(function (cache) {
cache.add('./test_cache.js').then(function() { }, function() { });
});
self.close();
ok(true, 'Should not crash on close()');
workerTestDone();

83
dom/cache/test/mochitest/worker_driver.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,83 @@
// 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) {
SimpleTest.waitForExplicitFinish();
var worker = new Worker('worker_wrapper.js');
worker.onmessage = function(event) {
if (event.data.type == 'finish') {
SpecialPowers.forceGC();
SimpleTest.finish();
} else if (event.data.type == 'status') {
ok(event.data.status, 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) {
ok(false, 'Worker had an error: ' + event.data);
SimpleTest.finish();
};
worker.postMessage({ script: script });
}

101
dom/cache/test/mochitest/worker_wrapper.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,101 @@
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// Worker-side wrapper script for the worker_driver.js helper code. See
// the comments at the top of worker_driver.js for more information.
function ok(a, msg) {
dump("OK: " + !!a + " => " + a + ": " + msg + "\n");
postMessage({type: 'status', status: !!a, msg: a + ": " + msg });
}
function is(a, b, msg) {
dump("IS: " + (a===b) + " => " + a + " | " + b + ": " + msg + "\n");
postMessage({type: 'status', status: a === b, msg: a + " === " + b + ": " + msg });
}
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 workerTestDone() {
postMessage({ type: 'finish' });
}
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);
});
postMessage({
type: 'getPrefs',
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);
});
postMessage({
type: 'getPermissions',
permissions: permissions
});
}
function workerTestGetVersion(cb) {
addEventListener('message', function workerTestGetVersionCB(e) {
if (e.data.type !== 'returnVersion') {
return;
}
removeEventListener('message', workerTestGetVersionCB);
cb(e.data.result);
});
postMessage({
type: 'getVersion'
});
}
function workerTestGetUserAgent(cb) {
addEventListener('message', function workerTestGetUserAgentCB(e) {
if (e.data.type !== 'returnUserAgent') {
return;
}
removeEventListener('message', workerTestGetUserAgentCB);
cb(e.data.result);
});
postMessage({
type: 'getUserAgent'
});
}
addEventListener('message', function workerWrapperOnMessage(e) {
removeEventListener('message', workerWrapperOnMessage);
var data = e.data;
try {
importScripts(data.script);
} catch(e) {
postMessage({
type: 'status',
status: false,
msg: 'worker failed to import ' + data.script + "; error: " + e.message
});
}
});